You are on page 1of 18

Unity3D BasicInfoandTutorials

AliArya(http://www.csit.carleton.ca/~arya) CarletonSchoolofInformationTechnology Fall2009


UnityPrimer
OneofthegreatestaspectsaboutUnityliesinitsGUIshospitabilityandfamiliarity.Youcanopenup UnityandtrythingsaroundandexperimentwiththedifferentpanelsoftheEditorfairlyintuitively.But incaseyoustartfeelinglost,heresasetoftutorialsandguidesthatarerecommendedasastarting pointforUnity: http://unity3d.com/support/documentation/video/ ThesevideosprovideaniceintroductiontoUnitysGUI,assetmanagement,scene manipulations,objectimporting,shortcuts,etc. UnityconvenientlysharesMayascontrolsandshortcuts.Herearesomeofthemostuseful ones: o CameraControl o [F]Bringselectedobjectintofocus o [W]Translate,[E]Rotate,[R]Scale o [Ctrl+D]Duplicate Similaritiescontinuetoappearevenatthefunctionallevel: o UnityComponentsMayaNodes o UnityScripts(JavaScript/C#)MayaScripts(MEL/PYTHON) Thatsreallyit.YouvegotwhatyouneedtostartusingUnity.Therestofthis documentationgoesoverthecreationoftheNativeDancedemoandreferencesthe providedvideotutorials.IfyourekeenonlearningmoreaboutUnity,visit http://unity3d.com/support/documentation/

BasicOperations:
InterfaceandControls
Thebasicinterfaceiscomprisedoffiveessentialsections:Scene,Game,Hierarchy,Projectand Inspector. Sceneshowsalloftheassetsorobjectsinthegame.Thisisalsowhereyoucaneditthesizeorposition oftheobjectsaswellascreatenewones.TheGamewindowiswherethegamecanbepreviewedin real time. Once the window is displayed, press the Play button to start the game running in real

time.

Hierarchy lists all of the attributes of the scene. Each asset can be selected individually or in groups. TheProjectwindowshowsallofthefilesintheprojectAssetfolder.Thisincludesalltextures,models, scriptsandmaterials.Simplyclickinganddraggingthemodelsontothescenewindowaddsthemtothe worldandincludestheminthehierarchywindow.TheInspectortabshowsthecomponentsandvalues of each object of the scene. This includes transformations or applied scripts such as animation or physics. TherearesomeshortcutstoaidinmanipulatingtheworldseenwithintheScenewindow.HoldingAlt+ theLeftmousekey,thewindoworbitsaroundtheobjectswithinthescenewindow.Alt+ theRightmousekeypanstheworld,ormovescloserandawayfromtheobjects.Alt+the Middlemousekey,zoomsinandout.Thereisalsothegizmotoolintherighthandcorner thatallowstheusertopickaspecificview:top,left,right,bottomandperspective. Ifyouaretryingtofindaspecificobjectwithintheworldinthescenewindow,clickontheobjectname withintheHierarchydockandthenpressthekeyF.Thisframestheobjectinthewindow.

ImportingFromMaya OncetheobjecthasbeenmadeinMaya,itisasimpleprocesstoimportittoUnity3D.Exportyourfile asanFBXfile,makingsurethatintheExportproperties,thattheFBXVersionissettoFBX200900.Ifyou haveananimatedobject,makesurethattheAnimationcheckboxistickedtoensurethattheanimation willexportaswell. Onceexported,placeallFBXfilesintotheUnity3Dprojectfolder,intheAssetsfolder.Tomakethingsa bitcleaner,anewfoldercanbecreatedwithintheAssetfoldertohelpmanageallofthepossiblefiles. In the unity file, the project dock will automatically update to show the new attributes in the Assets folder. From there, simply drag and drop the objects from the project dock onto the scene window. From Each there, the objects can be positioned, rotated and scaled as the need be. objectinthesceneisaninstanceoftheobject.Ifyouchangethesourcefile,allinstancesoftheobject willalsobechanged.Onceimported,theobjectscanstillbechangedinMaya.Simplyopentheoriginal FBX,makethechangesandsaveit.Theunityfilewillautomaticallyuploadthechanges.Thisgoesfor thetextureaswell.Openupthetexturefile,makethechangesandsaveit.

TerrainGeneration
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. StartUnityandmakeanewproject Gotohttp://unity3d.com/support/resources/unityextensions/terraintoolkitanddownloadthe Terraintoolkit. UnzipitanddoubleclicktheTerrainToolkit_v1.0.unitypackagefile. NowyouwillneedtoaddtheStandardUnityAssetstoyourUnityprojectiftheyarenotthere already(lookintheProjectdockforafoldercalledStandardAssets). ToaddthemiftheyarenotthererightclicktheprojectdockandclickimportnewAsset. GotoandselectC:/ProgramFiles(x86)/Unity/Editor/StandardPackages/Standard Assets.UnityPackage,andhitimport. Inyourunityprogramitwillaskyouwhatyouwanttoimport.Importeverything. InyourprojectswindowyoushouldnowseeaTerrainToolkitfile. GotoTerrain>CreateTerrain. Thisshouldcreateawhiteflatsquarewhichyouwillusetoraiseupandlowertocreateyour Terrain.Zoomoutuntilyoucanseeallofit. WithyournewlyTerrainobjectselectedintheHierarchywindowClick component>Terrain>TerrainToolkit.ThisshouldaddaTerrainToolkitcomponenttoyour Terrain. Nowyourgoingtowanttoaddsomelighttoyourscenetomakeiteasiertoseethechanges thatyoumake. GotoGameObject>CreateOther>DirectionalLight. SelectthetopviewtoviewitfromaboveanddragitintothemiddleofyourTerrain. Selectoneofthesideviewstoseeitfromtheside.YourTerrainwilldisappearbecauseitisa2D plane,butthedefaultcameraisatitslevelsojustdragyourDirectionalLightsoitsabovethe heightofthecamera. Rotateitsothattheraysarepointingonabouta45degreedownwardangle.Youcanalways repositionitafter.

12. 13. 14. 15.

16.

17. SelecttheTerrainagain.IntheTerrainToolkitcomponentmakesuretheCreate,Voronoi, buttonsareselectedaswellasthefirstfeaturetype.ChangethePresettoRollingHillsandslide theCellssliderfrom8to4andhitGenerate. 18. Keeponhittinggenerateuntilyougetsomethingsimilartothebelowpicturewherethepeaks areallclusteredtowardsonesideandthereisanexpanseofrelativelyflatgroundwhereyour charactercanwalkaroundin.

19. SelectthePerlinbuttonandapplythefollowingsettingsandclickGenerate.Thiswillgivethe landscapeabitmoreofarollinglookandmakeitmoreinteresting.Ifitturnsoutinawaythat

doesntlookgood(ifthelandscapeiseithertooflatortoobumpy)hitctrlZtoundothechanges andtrygeneratingitagain.

20. NowselectCreateandFracturalandinthePresetselectNoise.Wearegoingtoaddsomenoise tothelandscapetomakeitmoreinteresting.Usethefollowingsettings.

21. NowletsaddsomeErosiontosimulatemoreofanaturallook.ClickontheErosiontaband selectFullandinthepresetsselectlowrainfall,hardrock.

22. Nowletsaddsometexturestoourlandscapes.Clickonthetexturetab.Clickonaddtexture fourtimes.Nowapplythefollowingsettings.

23. Yourlandscapeshouldbemoreorlesscompleteatthispoint.Justtryexperimentingwiththe settingsofthingsifyoudontlikethelookofit.

Scripting
Scriptingalthoughconfusingattimesissimpleifyouthinkofitasaddingbitsofcodetomodels togetthemtobehaveinacertainway.Scriptingallowsyoutodefinehowtheyinteractwith eachotherandtoextendtheirfunctionalityandaddaffects.Itisarelativelyeasyprocessonce thebasicsareunderstood. 1. BeforewedoanyscriptingweshouldaddaFirstPersonControllertoourworldto interactwithit. 2. IfyouhaventalreadyimporttheStandardUnityAssets(seesteps46oftheTerrain Tutorial). 3. DeletethedefaultcameraUnitycreates;youdontneeditanylonger. 4. OnceimportedopentheStandardAssetsintheProjectdockandopenthePrefabs folder.YoushouldseetheFirstPersonControllerPrefab.Clickanddragitintoyour Sceneview.ViewitfromtheToptopositionitsomewhereinthemiddleofyour landscape.Thenviewitfromthesidetoplaceitaboveyourlandscapeandnotinor belowit.Itdoesntmatterifyouplaceitabitabovethelandscapebecausephysicsare appliedtoitandsoitwillbepulleddownbygravityuntilithitsyourlandscape.

5. PressPlay,youcannowusetheW,A,S,andD,keystomovearoundandthemousetolook.If youfindyourcharacteristooslow,selectthefirstpersoncontrollerandFPSWalkerScript changethespeedtoahigheronelike2025.

6. 7.

8.

9. 10. 11. 12.

13.

14.

WewillnowgiveourControllertheabilitytolaunchsmallprojectilesthatexplode. GotoGameObjectandselectcreateEmpty.RenameitLauncherandinthehierarchydockopen uptheFirstPersonControllerobjectandtheMainCameraobject.ClickanddragtheLauncher objectsothatitisachildoftheMainCameraobject. NowintheInspectorfortheLauncherputthesamecoordinatesinthex,y,andzastheMain ControllerObject.ThiswillmovetheLaunchertothesameplaceastheMainController(the Launcherdoesnthaveamodelattachedtoitsoitsinvisibleunlessselectedtotransform,scale, ortranslated). NowgotoGameObject,createother,andcreateasmallsphere.ThisiswhattheLauncherwill launch. NowgotoAssets>create>prefab,andclickanddragthespherefromthehierarchydockonto thenewprefabintheprojectdock.Theprefabshouldturnblue. Nowdeletethespherefromhierarchydockandselectthenewprefab. RenameitProjectile.Wearemakingaprefabofitbecauseitthenwheneverwewanttolaunch aspherethegamewilljustmakeaninstanceofitandspawnitattheplayerslocationandgive itavelocity. TogivetheLaunchertheabilitytofiresmallsphereweregoingtohavetocreateascriptto governitsbehaviorandthenattachittotheLauncher.Todothisgoto Assets>create>JavaScript.Thiswillcreateanewscript.RenameitLauncher. SelectitandhiteditintheInspector.Thiswillopenupasmallwindowtowritethecodeforthe scrip.Writethefollowing:

varprojectile:Rigidbody; functionFixedUpdate() { //iftheleftmousebuttonispressed if(Input.GetMouseButtonDown(0)) {

//createanewprojectileinstance,usethesameposition //androtationastheLauncher. varinstantiatedProjectile:Rigidbody=Instantiate (projectile,transform.position,transform.rotation); //Giveitaninitialforwardvelocity.Thedirectionis //alongthezaxisofthemissilelauncher'stransform. instantiatedProjectile.velocity= transform.TransformDirection(Vector3(0,0,50)); //Ignorecollisionsbetweenthemissileandthecharacter //controller.Thisissoitdosentaccidentlycollidewith //theplayerthemomementitiscreatedifthe Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);

15. Nowdragthescriptontoyourlauncherobject. 16. NowweneedtoaddarigidbodycomponenttoourspherebecauseintheLaunchcodewe specifiedthattheprojectileitlaunchesmustbearigidbody.Bymakingitarigidbodythiswill allowthephysicsenginetointeractwithit. 17. SelectyourProjectilePrefabandtoComponent>Physics>rigidbody. 18. NextweneedtotelltheLauncherthatthethingitisgoingtolaunchistheProjectilePrefab.To dothisweassignthisProjectilePrefabwehavecreatedtotheprojectilevariablethatisdefined intheLauncherJavaScript. 19. TodothisselectyourLauncherobject.IntheInspectorintheLaunchscriptsectionthereshould beaProjectilelinewithadropdownlistandnoneselected.Thislineisthevariablethatis definedinthecode. 20. NowwithoutdragyourProjectileprefabfromtheObjectsdockontothespaceintheLaunchers InspectorwheretheLaunchscriptwhereitsaysnone.ThiswillassigntheProjectilePrefabtobe theprojectiledefinedinthescript.Itshouldlooklikethis:

21. Nowifyourunthegameifyouclicktheleftmousebuttonyoucanshootsphericalprojectiles.

22. Nowwearegoingtoadddosomescriptingandaddsomethingssothatwhenthespherehits thegrounditwillexplodeandallobjectswiththerigidbodycomponentwillbepushedaway. 23. Tobeginwefirsthavetocreatetheexplosioneffect. 24. StartbygoingtoGameObject>CreateNew,tomakeanemptyGameObject. 25. WiththeGameObjectselectedgotoComponents>Particles>EllipsoidParticleEmitter,tocreate aparticleemitter. 26. Setittothefollowingsettingstogetsomethingthatlookslikeanexplosion.

27. NowgotoAssets>Create>Prefab. 28. ClickanddragyourParticleEmitterontothePrefabsothatitturnsblueandthenrenameyour PrefabtoExplosionanddeleteyourParticleEmitterfromthegameworld.

29. WealreadyhaveascriptfortheProjectile.Wewilladdsomebehaviorforitsothatwhenit landsitwillspawntheexplosionandthendeleteitselftomakeitlooklikeitexploded. 30. GotoAssets>create>JavaScript.Thiswillcreateanewscript.RenameitProjectile. 31. SelectitandhitEditintheInspector.Thiswillopenupasmallwindowtowritethecodeforthe scrip.Writethefollowing: varexplosion:GameObject; functionOnCollisionEnter(collision:Collision) { //findthecoordinateswherethespheretouchesthegroundandstoreit //inacontactpoint varcontact:ContactPoint=collision.contacts[0]; //makearotationpointingupwards varrotation=Quaternion.FromToRotation(Vector3.up,contact.normal); //Instantiatetheexplosionatthecontactpoint,withtheupwards //poinitngrotationvectortomakesureitisperpendiculartothe //surface varinstantiatedExplosion:GameObject=Instantiate(explosion, contact.point,rotation); //destroythesphereleavingonlytheexplosion Destroy(gameObject); } 32. AddthisprojectilescriptontoyourProjectilePrefab. 33. Nowwearegoingtocreateascripttogovernthebehavioroftheexplosion.Wewillmakeitlast onlyafewsecondandhaveitpushbackallrigidbodiesinitsblastradius. 34. GotoAssets>create>JavaScript.Thiswillcreateanewscript.RenameitExplosion. 35. SelectitandhitEditintheInspector.Thiswillopenupasmallwindowtowritethecodeforthe scrip.Writethefollowing: varexplosionTime=1.0; varexplosionRadius=5.0; varexplosionPower=2000.0; functionStart() { //Destroytheexplosioninxseconds Destroy(gameObject,explosionTime); //Findallnearbycolliders varcolliders:Collider[]=Physics.OverlapSphere(transform.position, explosionRadius); //Applyaforcetoallsurroundingrigidbodies. for(varhitincolliders) {

} 36. 37.

} //Ifwehaveaparticleemitterattached,emitparticlesfor.5seconds if(particleEmitter) { particleEmitter.emit=true; yieldWaitForSeconds(0.5); particleEmitter.emit=false; }

if(hit.rigidbody) { hit.rigidbody.AddExplosionForce(explosionPower, transform.position,explosionRadius); }

NowclickanddragtheExplosionScriptontotheExplosionPrefabtoaddittoit. NowthattheExplosionhasthedesiredbehaviorwecantelltheProjectilethatwhenitexplodes itneedstousethatExplosion. 38. ClickontheProjectilePrefabandintheinspector;intheProjectileScriptareayoushouldseea lineforExplosionthatsaysNone. 39. ClickanddragyourExplosionPrefabontothisspacetoassignittotheexplosionvariableusedin thatscript. 40. Itshouldlooklikethefollowing:

41. 42. 43. 44. 45.

Nowthatwehaveaddedanexplosiontothespheresitstimeforthemtohavesomethingto explode. GotoGameObject>CreateOther>Cube. WiththecubeselectedgotoComponents>Physics>Rigidbodytoaddtherigidbodycomponent tothecube. Nowselectthecubeandhitctrl+Dtoduplicateitseveraltimesandplacethemaroundthemap howeverwhichwayyouwant. Nowifyourunthegameyoushouldfindthatyoucannowlaunchsphereswhichwillexplode whentheyhitthegroundandiftheyexplodenearacubeitwillpushitbackormakeitflyup etc.

LinkstomoreInformation
http://unity3d.com/support/documentation/video/ ThesevideosprovideaniceintroductiontoUnitysGUI,assetmanagement,scene manipulations,objectimporting,shortcuts,etc. UnityconvenientlysharesMayascontrolsandshortcuts.Herearesomeofthemostuseful ones: o CameraControl o [F]Bringselectedobjectintofocus o [W]Translate,[E]Rotate,[R]Scale o [Ctrl+D]Duplicate Similaritiescontinuetoappearevenatthefunctionallevel: o UnityComponentsMayaNodes o UnityScripts(JavaScript/C#)MayaScripts(MEL/PYTHON) Thatsreallyit.YouvegotwhatyouneedtostartusingUnity.Therestofthis documentationgoesoverthecreationoftheNativeDancedemoandreferencesthe providedvideotutorials.IfyourekeenonlearningmoreaboutUnity,visit http://unity3d.com/support/documentation/

LocalVideoTutorials
Thereareacouplevideotutorialsincludedinthispackage.Theyexplainthefollowing:
VideoUnity_Stage1:AssetPreparationandProjectSetup Starts with the procedure of opening up the program Unity 3D and importing the Standard Assets library.Next,itdescribesthebasicsofexportingacompatiblefilefromMayatobeusedintheunity projectfile.Thisincludesexportingamodelwithananimation.Unityautomaticallyupdates,reflecting thenewobjectsplacedintheAssetsfolderoftheunityproject. AssetWorkflow: http://unity3d.com/support/documentation/Manual/Asset%20Workflow.html ImportingfromMaya: http://unity3d.com/support/documentation/Manual/HOWTOImportObjectMaya.html

VideoUnity_Stage2:CreatingScenes Starts interacting in Unity 3D with the exported models from Maya. It goes through texturing these modelsandaddingcomponentssuchasdetectingcollision.Forananimatedobject,thereisaspecific component property to add animations to the object. It refers to specific frames from the Maya animation.Next,itshowshowtocreateasimpleterrain. CreatingScenes: http://unity3d.com/support/documentation/Manual/Creating%20Scenes.html CharacterAnimation: http://unity3d.com/support/documentation/Manual/CharacterAnimation.html Terrains: http://unity3d.com/support/documentation/Manual/Terrains.html

VideoUnity_Stage3:ScriptingandPublishingBuilds ThisvideoexplorersusingaFirstPersonControllerandaddingaudiotoanobject.Italsodemonstrates how to create light in the world. Next, it travels through the details of triggering an animation by creatinganinvisibleborderthatoncetheFirstPersonControllerpasses,theanimationwillstart.This involvessomebasicscriptingthatisalsodemonstrated. ScriptingReference(referencesbothJavaScriptandC#): http://unity3d.com/support/documentation/ScriptReference/index.html ComponentReference: http://unity3d.com/support/documentation/Components/Components.html Colliders(CollisionDetection,PhysicsandTriggers): http://unity3d.com/support/documentation/Components/classBoxCollider.html PublishingBuilds: http://unity3d.com/support/documentation/Manual/Publishing%20Builds.html

You might also like