Unity 5 From Zero to Proficiency (Foundations): A

Astep-by-stepguidetocreatingyourfirstgame.
PatrickFelicia
Unity5FromZerotoProficiency
(Foundations)
Copyright©2015PatrickFelicia
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinretrievalsystems,or
transmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher(PatrickFelicia),exceptinthecaseofbriefquotationsembeddedincritical
articlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressedorimplied.Neithertheauthoranditsdealersanddistributors
willbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlyby
thisbook.
Firstpublished:October2015
PublishedbyPatrickFelicia
Credits
Author:PatrickFelicia
AbouttheAuthor
PatrickFeliciaisalecturerandresearcheratWaterfordInstituteofTechnology,wherehe
teachesandsupervisesundergraduateandpostgraduatestudents.HeobtainedhisMScin
MultimediaTechnologyin2003andPhDinComputerSciencein2009fromUniversity
CollegeCork,Ireland.Hehaspublishedseveralbooksandarticlesontheuseofvideo
gamesforeducationalpurposes,includingtheHandbookofResearchonImproving
LearningandMotivationthroughEducationalGames:MultidisciplinaryApproaches
(publishedbyIGI),andDigitalGamesinSchools:aHandbookforTeachers,publishedby
EuropeanSchoolnet.PatrickisalsotheEditor-in-chiefoftheInternationalJournalof
Game-BasedLearning(IJGBL),andtheConferenceDirectoroftheIrishSymposiumon
Game-BasedLearning,apopularconferenceongamesandlearningorganizedthroughout
Ireland.
SupportandResourcesforthisBook
Sothatyoucancompletetheprojectpresentedinthisbookseamlessly,awebsitehasbeen
setup,anditincludesallthematerialyouneedtocompletetheprojectpresentedinthe
nextchapters(e.g.,texturesorsolutionsforeachchapter),aswellasbonusmaterial.
Toavailofthiscontent,youcanopenthelink:
http://www.learntocreategames.com/learn-unity-ebook/.
http://www.learntocreategames.comalsoprovidesyouwiththeopportunitytosubscribetoa
newsletter,obtainexclusivediscountsandoffersonnewbooks,andgainaccesstovideo
tutorialsoncreatinggames.
Whyshouldyousubscribe?
Bethefirsttobenotifiedofnewresourcesavailable.
Receiveregularupdatesandtutorialsoncreatinggames.
Receiveanewsletterwithtipsandhintsongamedevelopment.
ThisbookisdedicatedtoHelena
Preface
AfterteachingUnityforover4years,Ialwaysthoughtitcouldbegreattofindabookthat
couldgetmystudentsstartedonUnityinafewhoursandthatshowedthemhowtomaster
thecorefunctionalitiesofferedbythisfantasticsoftware.
ManyofthebooksthatIfoundweretooshortanddidnotprovideenoughdetailsonthe
whybehindtheactionsrecommendedandtaken;otherbookswerehighlytheoretical,and
Ifoundtheylackedpracticalityandwouldnotgetmystudents’fullattention.Inaddition,I
oftenfoundthatgamedevelopmentmaybepreferredbythosewithaprogramming
backgroundbutthatthosewithanArtsbackground,eveniftheywantedtogettoknow
howtocreategames,oftenhadtofacetheissueoflearningtocodeforthefirsttime.
Asaresult,Istartedtoconsideraformatthatwouldcoverboth:beapproachable(evento
thestudentswithnoprogrammingbackground),keepstudentshighlymotivatedand
involvedusinganinterestingproject,coverthecorefunctionalitiesavailableinUnityto
getstartedongameprogramming,provideanswerstocommonquestions,andalso
provide,ifneedbe,aconsiderableamountofdetailsforsometopics.
ThisbookseriesentitledFromZerotoProficiencydoesjustthis.Inthisbookseries,you
havetheopportunitytoplayaroundwithUnity’scorefeatures,andessentiallythosethat
willmakeitpossibletocreateaninteresting3Dgamerapidly.Afterreadingthisbook
series,youshouldfinditeasiertouseUnityanditscorefunctionalities.
Thisbookseriesassumesnopriorknowledgeonthepartofthereader,anditwillgetyou
startedonUnitysothatyouquicklymasterallthewonderfulfeaturesthatthissoftware
providesbygoingthroughaneasylearningcurve.Bycompletingeachchapter,and
followingstep-by-stepinstructions,youwillprogressivelyimproveyourskills,become
moreproficientinUnity,andcreateasurvivalgameusingUnity’scorefeaturesinterms
ofprogramming(C#andJavaScript),gamedesign,anddraganddropfeatures.
InadditiontounderstandingandbeingabletomasterUnity’scorefeatures,youwillalso
createagamethatincludesmanyofthecommontechniquesfoundinvideogames,
including:leveldesign,objectcreation,textures,collectiondetection,lights,weapon
creation,characteranimations,particles,artificialintelligence,andmenus.
Throughoutthisbookseries,youwillcreateagamethatincludesbothindoorandoutdoor
environmentswheretheplayerneedstofindsitswayoutoftheformerthroughtunnels,
escalators,traps,andotherchallenges,avoidoreliminateenemiesusingweapons(i.e.,
gunorgrenades),driveacarorpilotanaircraft.
YouwilllearnhowtocreatecustomizedmenusandsimpleuserinterfacesusingUnity’s
newUIsystem,andanimateandgive(artificial)intelligencetoNon-PlayerCharacters
(NPCs)whowillbeabletofollowyourcharacterusingMecanimandMavmesh
navigation.
Finallyyouwillalsogettoexportyourgameforthewebatthedifferentstagesofthe
books,sothatyoucanshareitwithfriendsandgetsomefeedback.
ContentCoveredbythisBook
Chapter1,TheBenefitsofUsingUnity,providesgeneralinformationongameengines
andexplainswhyyoushouldusesuchsoftware,andhow,byusingUnitymore
specifically,youcancreategamesseamlessly.
Chapter2,InstallingUnityandBecomingFamiliarwiththeInterface,takesyouthrough
theveryfirststepsofinstallingUnityandbecomingfamiliarwiththeinterface.Itwillalso
showyouthedifferentshortcutsnecessarytonavigatethroughscenesandprojectsin
Unity.
Chapter3,CreatingandExportingyourFirstScene,getsyoutocreateandexportyour
firstscenebycombiningbuilt-inobjects.Youwilllearnhowtomanageobjects,apply
texturesandcolors,andtransformobjectstocreateasimplescene.
Chapter4,TransformingBuilt-inObjectstoCreateanIndoorScene,explainshowyou
cancreateanindoorscene(i.e.,amaze)withbuilt-inshapes.Youwillalsoworkwithand
managelightsinyourscenetosettheatmosphereandnavigatethroughthescenewitha
First-PersonController.
Chapter5,CreatinganoutdoorScenewithUnity’sBuilt-inTerrainGenerator,explains
howyoucancreateanoutdoorscenewithwater,hills,sandybeachesandpalmtreesusing
Unity’sbuilt-inassets.Youwillalsobeabletoaddandcontrolacarandaplane.
Chapter6providesanswerstofrequentlyaskedquestionsbasedonspecificthemesand
topics(e.g.,assetscreationortransformations).
Chapter7summarizesthetopicscoveredinthisbookandalsoprovidesuseful
informationifyouwouldliketoprogressfurtherwiththisbookseries.
WhatyouNeedtoUsethisBook
Tocompletetheprojectpresentedinthisbook,youonlyneedUnity5.0(oramorerecent
version)andtoalsoensurethatyourcomputeranditsoperatingsystemcomplywith
Unity’srequirements.Unitycanbedownloadedfromtheofficialwebsite
(http://www.unity3d.com/download),andbeforedownloading,youcancheckthatyourcomputer
isuptoscratchonthefollowingpage:http://www.unity3d.com/unity/system-requirements.Atthetime
ofwritingthisbook,thefollowingoperatingsystemsaresupportedbyUnityfor
development:WindowsXP(i.e.,SP2+,7SP1+),Windows8,andMacOSX10.6+.In
termsofgraphicscard,mostcardsproducedafter2004shouldbesuitable.
Intermsofcomputerskills,allknowledgeintroducedinthisbookwillassumenoprior
programmingexperiencefromthereader.Thisbookdoesnotincludeanyscripting(this
willbeintroducedinthesecondbookintheseries).Sofornow,youonlyneedtobeable
toperformcommoncomputertaskssuchasdownloadingitems,openingandsavingfiles,
andbecomfortablewithdragginganddroppingitemsandtyping.
WhothisBookisfor
Ifyoucanansweryestoallthesequestions,thenthisbookisforyou:
1.AreyouatotalbeginnerinUnityorprogramming?
2.WouldyouliketobecomeproficientinthecorefunctionalitiesofferedbyUnity?
3.Wouldyouliketoteachstudentsorhelpyourchildtounderstandhowtocreategames?
4.Wouldyouliketostartcreatinggreatgames?
5.AlthoughyoumayhavehadsomepriorexposuretoUnity,wouldyouliketodelve
moreintoUnityandunderstanditscorefunctionalitiesinmoredetail?
WhothisBookisnotfor
Ifyoucanansweryestoallthesequestions,thenthisbookisnotforyou:
1.Canyoualreadyeasilycreatea3DgamewithUnitywithbuilt-inobjects,controllers,
cameras,lights,andterrains?
2.AreyoulookingforareferencebookonUnityprogramming?
3.Areyouanexperienced(oratleastadvanced)Unityuser?
Ifyoucanansweryestoallthreequestions,youmayinsteadlookforthenextbooksinthe
series.Toseethecontentandtopicscoveredbythesebooks,youcanchecktheofficial
website(www.learntocreategames.com/learn-unity-ebook).
HowyouwillLearnfromthisBook
Becauseallstudentslearndifferentlyandhavedifferentexpectationsofacourse,this
bookisdesignedtoensurethatallreadersfindalearningmodethatsuitsthem.Therefore,
itincludesthefollowing:
Alistofthelearningobjectivesatthestartofeachchaptersothatreadershavea
snapshotoftheskillsthatwillbecovered.
Eachsectionincludesanoverviewoftheactivitiescovered.
Manyoftheactivitiesarestep-by-step,andlearnersarealsogiventheopportunityto
engageindeeperlearningandproblem-solvingskillsthroughthechallengesofferedatthe
endofeachchapter.
Eachchapterends-upwithaquizandchallengesthroughwhichyoucanputyourskills
(andknowledgeacquired)intopractice,andseehowmuchyouknow.
Thebookfocusesonthecoreskillsthatyouneed;somesectionsalsogointomore
detail;however,onceconceptshavebeenexplained,linksareprovidedtoadditional
resources,wherenecessary.
FormatofeachChapterandWriting
Conventions
Throughoutthisbook,andtomakereadingandlearningeasier,textformattingandicons
willbeusedtohighlightpartsoftheinformationprovidedandmakeitmorereadable.
Thefullsolutionfortheprojectpresentedinthisbookisavailablefordownloadonthe
officialwebsite(http://www.learntocreategames.com/learn-unity-ebook).Soifyouneedto
skipasection,youcandoso;youcanalsodownloadthesolutionforthepreviouschapter
thatyouhaveskipped.
SpecialNotes
Eachchapterincludesresourcesectionssothatyoucanfurtheryourunderstandingand
masteryofUnity;theseinclude:
Aquizforeachchapter:thesequizzesusuallyinclude10questionsthattestyour
knowledgeofthetopicscoveredthroughoutthechapter.Thesolutionsareprovidedonthe
companionwebsite.
Achecklist:itconsistsofbetween5and10keyconceptsandskillsthatyouneedtobe
comfortablewithbeforeprogressingtothenextchapter.
Challenges:eachchapterincludesachallengesectionwhereyouareaskedtocombine
yourskillstosolveaparticularproblem.
Author’snotesappearasdescribedbelow:
Author’ssuggestionsappearinthisbox.
Checkliststhatincludetheimportantpointscoveredinthechapterappearasdescribed
below:
Item1forchecklist
Item2forchecklist
Item3forchecklist
HowCanYouLearnBestfromthisBook
Talktoyourfriendsaboutwhatyouaredoing.
Weoftenthinkthatweunderstandatopicuntilwehavetoexplainittofriendsand
answertheirquestions.Byexplainingyourdifferentprojects,whatyoujustlearned
willbecomeclearertoyou.
Dotheexercises.
Allchaptersincludeexercisesthatwillhelpyoutolearnbydoing.Inotherwords,
bycompletingtheseexercises,youwillbeabletobetterunderstandthetopicand
gainpracticalskills(i.e.,ratherthanjustreading).
Don’tbeafraidofmakingmistakes.
Iusuallytellmystudentsthatmakingmistakesispartofthelearningprocess;the
moremistakesyoumakeandthemoreopportunitiesyouhaveforlearning.Atthe
start,youmayfindtheerrorsdisconcerting,orthattheenginedoesnotworkas
expecteduntilyouunderstandwhatwentwrong.
Exportyourgamesearly.
Itisalwaysgreattobuildandexportyourfirstgame.Evenifitisrathersimple,itis
alwaysgoodtoseeitinabrowserandtobeabletoshareitwithyoufriends.
Learninchunks.
Itmaybedisconcertingtogothroughfiveorsixchaptersstraight,asitmaylower
yourmotivation.Instead,giveyourselfenoughtimetolearn,goatyourownpace,
andlearninsmallunits(e.g.,between15and20minutesperday).Thiswilldoat
leasttwothingsforyou:itwillgiveyourbrainthetimeto“digest”theinformation
thatyouhavejustlearned,sothatyoucanstartfreshthefollowingday.Itwillalso
makesurethatyoudon’t“burn-out”andthatyoukeepyourmotivationlevelshigh.
Feedback
WhileIhavedoneeverythingpossibletoproduceabookofhighqualityandvalue,I
alwaysappreciatefeedbackfromreaderssothatthebookcanbeimprovedaccordingly.If
youwouldliketogivefeedback,[email protected].
DownloadingtheSolutionsfortheBook
Youcandownloadthesolutionsforthisbookaftercreatingafreeonlineaccountat
www.learntocreategames.com/learn-unity-ebook.Onceyouhaveregistered,alinktothefileswillbe
senttoyouautomatically.
ImprovingtheBook
Althoughgreatcarewastakenincheckingthecontentofthisbook,Iamhuman,andsome
errorscouldremaininthebook.Asaresult,itwouldbegreatifyoucouldletmeknowof
anyissueorerroryoumayhavecomeacrossinthisbook,sothatitcanbesolvedandthe
bookupdatedaccordingly.Toreportanerror,youcanemailme([email protected])
withthefollowinginformation:
Nameofthebook.
Thepagewheretheerrorwasdetected.
Describetheerrorandalsowhatyouthinkthecorrectionshouldbe.
Onceyouremailisreceived,theerrorwillbechecked,and,inthecaseofavaliderror,it
willbecorrectedandthebookpagewillbeupdatedtoreflectthechangesaccordingly.
SupportingtheAuthor
Alotofworkhasgoneintothisbookanditisthefruitoflonghoursofpreparation,
brainstorming,andfinallywriting.Asaresult,Iwouldaskthatyoudonotdistributeany
illegalcopiesofthisbook.
Thismeansthatifafriendwantsacopyofthisbook,s/hewillhavetobuyitthroughthe
officialchannels(i.e.,throughAmazon,lulu.com,orthebook’sofficialwebsite:
www.learntocreategames.com/learn-unity-ebook).
Ifsomeofyourfriendsareinterestedinthebook,youcanreferthemtothebook’sofficial
website(http://www.learntocreategames.com/learn-unity-ebook)wheretheycaneitherbuythebook,
enteramonthlydrawtobeinforachanceofreceivingafreecopyofthebook,ortobe
notifiedoffuturepromotionaloffers.
1
TheBenefitsofUsingUnity
ThischapterisanintroductiontogameenginesandUnity,anditexplainsthebenefits
broughtbygameengines,andmorespecificallyhowUnitycanhelpyoutocreategames
seamlessly.Themostrecentfeaturesareexplained,andexamplesofgamescreatedin
Unityarealsogivensothatyoucanevaluatethepotentialofthisgameengine.
IfyoualreadyknowofthebenefitsofUnityandgameenginesingeneral,youcanskipto
thenextchapter.
Aftercompletingthissection,youshouldbeableto:
Understandtheconceptofgameengines.
KnowthefeaturesintroducedbyUnity5.
UnderstandthebenefitsofusingUnity.
Whatisagameengineandshouldyouuseone?
Unityisasoftwarethatmakesitpossibletocreatevideogameswithoutknowingsomeof
theunderlyingtechnologiesofgamedevelopment,sothatpotentialgamedevelopersonly
needtofocusonthegamemechanicsandemployahigh-levelapproachtocreatinggames
usingprogrammingandscriptinglanguagessuchasC#orJavaScript.Thetermhigh-level
herereferstothefactthat,whenyoucreateagamewithagameengine,youdon’tneedto
worryabouthowthesoftwarewillrenderthegameorhowitwillcommunicatewiththe
graphicscardtooptimizethespeedofyourgame.Sousingagameenginewould
generallyofferthefollowingfeaturesandbenefits:
Accelerateddevelopment:gameenginesmakeitpossibletofocusonthegame
mechanics.Becausebuilt-inlibrariesareavailableforcommonmechanicsandfeatures,
thesedonotneedtoberebuiltfromscratch,andprogrammerscanusethemstraightaway
andsavetime(e.g.,fortheuserinterfaceortheartificialintelligence).
IntegratedDevelopmentEnvironment(IDE):anIDEhelpstocreate,compile,and
manageyourcode,andincludessomeusefultoolsthatmakedevelopmentanddebugging
moreefficient.
GraphicalUserInterface(GUI):whilesomegameenginesarebasedonlibraries,most
commongameenginesmakeitpossibleforuserstocreateobjectsseamlesslyandto
performcommontaskssuchastransforming,texturing,andanimating,throughdragand
dropfeatures.Anotheradvantageofsuchsoftwareisthatyoucanunderstandandpreview
howthegamewilllookwithouthavingtocompilethecode(e.g.,throughscenes).
Multi-platformdeployment:withcommongameengines,itispossibletoexportthe
gameyouhavecreatedtoseveralplatformswiththeclickofabutton(e.g.,fortheweb,
iOS,orAndroid)withouthavingtorecodetheentiregame.
AdvantagesofusingUnity
Thereareseveralgameenginesavailableoutthere;however,Unityhasproventobeone
ofthebestengines.Ithasbeenusedbygamedevelopersforseveralyearsandhasbeen
employedtoproducesuccessful3Dand2Dgames.Severalofthesetitlecanbeseenon
Unity’swebsite(http://unity3d.com/gallery/made-with-unity/game-list).
WithUnity,youcancreate2Dor3Dgamesandproduceseveraltypesofgamegenres
includingFirst-PersonShooters(FPS),MassiveMultiplayerOnlineRolePlayingGames
(MMORPG),casualgames,adventuregames,andmuchmore.
Inadditiontobeingabletocreatehigh-qualitygameswithaneasy-to-useinterface,Unity
makesitpossibletoexportgamestoawiderangeofplatforms,includingAndroid,iOS,
WindowsPhone8,Mac,Linux,PS3,orXBOX360.
Unityincludesallthenecessarytoolsthatyouneedtocreategreatgamesanditalso
simplifiestheapplicationofusefultechniquestoimprovethequalityofyourgame.For
example,itincludesMonoDevelop,anIDEthatwillhelpyoutocodefaster,built-in
ArtificialIntelligence(AI)modules(e.g.,navmeshnavigation)thatyoucanusewithno
priorknowledgeofAI,lights,built-inobjects,orafinitestatemachinethatyoucanapply
toyourcharactersforcustomizedbehaviors.
Finally,inordertocontrolthegame,youcanusehigh-levelprogrammingandscripting
languagessuchasBoo,C#orJavaScript.Thisisusefulforthosewhohavealreadybeen
exposedtooneoftheselanguagestotransfertheirskillstogameprogramminginUnity.It
alsoprovidesprogrammerswithachoicedependingontheirlevelofproficiency.For
example,beginnersmaypreferJavaScript,whilemoreadvancedcodersmayprefertouse
C#(i.e.,forthosewithpriorexperienceofObjectOrientedProgramming).
NoveltiesintroducedinUnity4.6and5.0
Currently,Unityisinversion5.WhiletheUnityteamisconsistentlyworkinghardto
improvethefeaturesandfunctionalitiesincludedwithin,thesoftwarehasbeenthrougha
steadypaceofchangesandimprovementssinceitsfirstlaunch.Bugsarebeingfixed
quicklyandtheUnityteamisalwayslookingintomakingthissoftwareeasiertouseand
moreefficient.
Whilesubsequentversionswill,withoutadoubt,introduceinterestingnewfeatures,most
oftheskillsandknowledgethatyouwillacquireinthisbookshouldstillberelevant.
Unity4introducedmuch-awaitedexcitingfeaturessuchasMecanim(i.e.,forcharacter
animations).Unity4.6alsomarkedanimportantstepforusersasitincludedUnityUI,a
featurethatmakesitpossibletocreatesmoother,dynamicandmoreintuitiveGraphical
UserInterfaces(GUI)foryourgame.Meanwhile,amongstotherthings,previously
premiumfeaturesfoundinversion4.x(e.g.,navmeshandiOSorAndroidexport)arenow
availableforfreeinUnity5personaledition.
Unity5.0wasreleasedin2015andhasbroughtsignificantchangesinboththewaythe
softwareislicensedanditsfeatures.FromUnity5.0onwards,thesoftwarecomesintotwo
mainversions:thepersonaleditionandtheprofessionaledition.Fortheformer,allthe
featuresoftheengineareavailable.Inthelatter,yougainaccesstoadditionalfeatures
suchascustomizablesplashscreen,teamlicenses,orgameperformancereporting.In
termsoffeatures,Unity5.0introducesawiderangeoffeaturesthatwillmakeyourgame
lookmorerealisticandpolished,includingglobalillumination(forimprovedillumination
whenusingbothstaticanddynamicobjects),theAudioMixerorexporttoWebGL.
Asyoucansee,thereismuchtolearninUnityandwewillfocusonUnity’score
technologiesinthisbookseries.
Levelroundup
Summary
ThischapterhasdescribedsomeofthereasonswhyyoushoulduseUnityandsomeofits
corefunctionalities.Youhavealsodiscoveredtheconceptofgameengine,thebenefits
broughtbygameengines,andhowUnitycanspecificallymakeiteasierforyoutoget
startedwithgamedevelopment.
2
InstallingUnityandBecomingFamiliar
withtheInterface
ThischapterhelpsyoutoprogressivelybecomefamiliarwithUnitybyexplainingand
illustratinghowtoinstallthissoftware,andhowthedifferentviewsandcorefeaturescan
beemployed.Youwillalsolearntocreateyourfirstprojectandscene,usingpredefined
objectssuchasboxes.AfterlearningthefeaturesofthedifferentviewsavailableinUnity,
youwilllearnhowtonavigatethroughascene(tolookatobjects),beforecreatingyou
veryfirstgamewithbuilt-inobjectsandapplyingcolorsandtextures.
Aftercompletingthissection,youshouldbeableto:
BemoreconfortablewithUnity’sinterface.
UnderstandtheroleandlocationofthedifferentviewsinUnity.
Understandtheroleofcolliders.
Addandconfigurecamerasandlights.
Knowanduseshortcutstomanipulateobjects(e.g.,move,scale,resize,duplicate,or
delete)andmovetheviewaccordingly(e.g.,panorrotate).
UsetheInspectorview.
Createandapplycolorsandtexturestoobjects.
Createandcombinesimplebuilt-inshapes.
Knowhowtosearchforandorganizeassetsinyourgameefficiently.
Navigatethroughyoursceneandseeitfrombothfirst-andthird-personviews.
DownloadingUnity
NowthatyouhavehadanoverviewofUnityandgameengines,itistimeforustostart
usingUnity.Unityisavailablefordownload,forfree,fromtheUnitywebsiteandthenext
stepswillshowyouhowtodownloadit:
1.Openthefollowinglink:http://unity3d.com/unity/system-requirements.Thiswillhelpyoutocheck
thatyourcomputercomplieswithUnity’srequirements.
2.Onceyouhavecheckedtherequirements,wecandownloadUnitybyopeningthe
followingpage:http://unity3d.com/get-unity/download?ref=personal
3.Oncethepageisopened,alinktothecurrentversionofUnityisprovided(i.e.,the
installer).ThispagewillautomaticallydetectwhetheryoucomputerisrunningMacOSX
orWindows,andbyclickingonthelink,thecorrespondinginstallerwillbedownloaded
toyourcomputer(i.e.,.dmgforMacOSXor.exeforWindows),asdescribedonthenext
figure.NotethatdirectlinkstoeitherversionareavailableinUnity’sarchive
(http://unity3d.com/get-unity/download/archive).
Figure2‑1:DownloadingUnityfromtheofficialwebsite
ItispossibletodownloadpreviousversionsofUnityfromUnity’sarchive
(http://unity3d.com/get-unity/download/archive).Thismaybeusefulifyouworkfromtwodifferent
locationsforyourUnityprojectandifeachcomputerhasadifferentversionofUnity
installed.Ifthisisthecase,youwillbeabletoopenprojectsbuiltwithanolderversion
ofUnitywithanewversionofUnity(e.g.,aprojectinitiallycreatedwithUnity4.xcan
beopenedwithUnity5.x);however,afteropeningaprojectthatwascreatedwithan
olderversionofUnity,thisprojectisconvertedtothenewversionofUnityandcanno
morebeopenedwiththepreviousversion(i.e.,aprojectinitiallycreatedwithUnity4.x,
andthenopenedwithUnity5.xcan’tbeopenedanymorewithUnity4.x).Youmayalso
backupyouprojectbeforeanyfileconversion,forsafety.
OncewehavedownloadedUnity,wecanlaunchtheinstallerandfollowtheonscreen
instructions.Oncethesoftwareisinstalled,youcanprogresstothenextsection.
LaunchingUnity
OnceyouhavesuccessfullyinstalledUnity,wecannowlaunchit.Uponthefirsttimeyou
openUnity,youmayneedtoprovideyouremailaddress,sothatyoucanreceiveregular
updatesfromtheUnityteam.Thisshouldbereallyusefultokeepup-to-datewithmajor
announcementsforthissoftware.Youmayalsobeaskedwhetheryouwouldliketo
activatetheProversion;however,forthepurposeofthistutorial,youonlyneedtousethe
freeversion(i.e.,personaledition).
Afterhavingprovidedyouremaildetailsaswellaschoosingthefreeversionofthe
software,wecanstarttoenjoyUnity.
AfterlaunchingUnity,thefollowingwindowappears:
Figure2‑2:LaunchingUnityforthefirsttime
ThepreviousfigureshowsawindowlabeledProjectsthatlistsallprojectsthatyouhave
beenworkingonpreviously(i.e.,emptyfornow).IfyouclickonthelabelGetStarted,
youcanaccessawelcomevideofromtheUnityTeamthatbrieflydescribesthenew
featuresintroducedbythisversion.Youmayalsonoticethreebuttonsatthebottomofthe
window,labeledCommunity,Documentation,andTutorials,whichwilltakeyoutothe
relevantresourcesontheUnitywebsitealso.(i.e.,Unityforums,theofficial
documentationforUnity,orofficialUnitytutorials).
Let’spressthebuttonlabeledNewProjecttocreateanewproject.Thefollowingwindow
shouldappear:
Figure2‑3:Creatinganewproject
Inthiswindow,wewillspecifyanameforourproject,aswellasalocation.
InthesectionProjectName:typeanameofyourchoice,forexamplemyFirstProject.
IntheLocationsection:clickonthethreedotslocatedtotherightofthelabelLocation
andselectwhereonyourharddriveyouwouldliketosavetheproject.
2D/3D:forthisproject,wewillbeusingathree-dimensionalenvironment;therefore,we
willclickonthe3Dicon.Aswewillseelater,youcancreateboth2Dand3Dgameswith
Unity,andprojectsaresetupaccordingly.
Assets/Packages:wewillleavethisoptionasdefault,aswewillidentifylatertheassets
thatwillbenecessaryforourfirstproject.
Onceyouhaveenteredthisinformation,youcannowclickonthebuttonlabeledCreate
Project.
WhenUnitystarts-up,awindowlabeledUnityEditorUpdateCheckappears.This
window,illustratedbelow,istheretocheckwhetheryouhavethelatestversionofUnity
andtoletyouknowofanyrecentupdatesavailable.Ifanupdateisnecessary,youcan
installit;ifyouwouldprefernottoseethismessagedisplayedeverytimeyoustartUnity,
youcanuncheckthecorrespondingboxlabeledCheckforUpdatesaccordingly.
Figure2‑4:AutomaticallycheckingforUnityupdates
Unityprovideslinkstoofficialforumsanddocumentationfromthemain(i.e.,top)
menu:Help|UnityForumsorHelp|UnityManual.
Understandingandbecomingfamiliarwiththeinterface
AsforanymajorversionofUnity,onceyouopenthissoftwareforthefirsttime,aproject
isalreadyloadedandreadytoplay.Thisprojectusuallyillustratesandbringsforwardthe
mostinterestingfeaturesavailableinthelatestversion.InUnity5.x,thisprojectiscalled
VikingVillageandincludesaveryinterestingandfunleveltoplayandtodiscover.All
projectsdeliveredinversions1,2,3and4ofUnityarealsoavailablethroughtheAssets
Store,whichisavailablefromUnitybyselectingWindow|AssetsStorefromthemain
menu.Atthispointintime,althoughsomedemolevelshavebeenreleasedforUnity5.0,
anofficialplayablelevelhasnotbeenreleasedyet.Thisisthereasonwhywewillbe
usingthedemoprojectcalledVikingVillageinthenextsections.
AfterlaunchingUnity,wecannoticethatitincludesseveralwindowsorganizedina
(default)layout.Eachofthesewindowsincludesalabel(usuallyinthetop-leftcorner)of
thewindow,andallcanbemovedaround,ifnecessary,byeitherchangingthelayout
(Window|Layouts|…)orbydragginganddroppingthecorrespondingtabforawindow
(thiswillmovetheviewtowhereyouwouldlikeittoappearwithinthewindow).Inthe
defaultlayout,thefollowingviewsappearonscreen(asdescribedinthenextscreenshot,
clockwisefromthetopleftcorner):
1.TheHierarchywindow(thecorrespondingshortcutisCTRL+4):thiswindoworview
listsalltheobjectscurrentlypresentinyourscene;thesecouldinclude,forexample,basic
shapes,3Dcharacters,orterrains.Thisviewalsomakesitpossibletoidentifyahierarchy
betweenobjects;forexample,wecanseeinthisviewifsomeobjectshavechildrenor
parents(wewillexplorethisconceptlater).
2.TheSceneview(CTRL+1):thiswindowdisplaysthecontentofascene(ortheitem
listedintheHierarchyview)sothatyoucanvisualizethemandmodifythemaccordingly
usingthemouse(e.g.,move,scale,etc.).
3.TheGameview(CTRL+2):thiswindowmakesitpossibletovisualizethesceneasit
willappearinthegame(i.e.,throughthelensesoftheactivecamera).
4.TheInspectorview(CTRL+3):thiswindowdisplaysinformation(i.e.,properties)on
theobjectcurrentlyselected.
5.TheConsolewindow(SHIFT+CTRL+C):thiswindowdisplaysmessageseitherprinted
fromthecodebytheuser(usingkeywords)orbyUnity.Theseincludewarningsorerror
messagesrelatedtoyourprojectorcode.
6.TheProjectwindow(CTRL+5):thiswindowincludesalltheassetsavailableandused
foryourproject.Theseinclude3Dmodels,sounds,ortextures.
Figure2‑5:MainwindowsandviewsinUnity
Thesceneview
Wewillusethisviewtocreateandvisualizethesceneforourgame.Whenyoucreatea
project,youcanincludeseveralsceneswithin.Asceneiscomparabletoalevel,and
scenesthatareincludedinthesameprojectcansharesimilarresources,sothatassetsare
importedonceandsharedacross(orusedin)allscenes.TheSceneandGameviewsare
displayedinthesamewindow,andbotharerepresentedbyacorrespondingtab.By
default,theSceneviewisactive;however,itispossibletoswitchtotheGameviewby
clickingonthetablabeledGame.Forexample,ifweclicksuccessivelyontheGameand
Scenetabs,wecanseetheviewfromboththeperspectivesofyoureyes(i.e.,sceneview)
andtheactivecamerapresentinthescene(Gameview)asillustratedinthenextfigures.
Figure2‑6:TheSceneview
Figure2‑7:TheGameview
Notethatyoucanalsorearrangethelayouttobeableto,forexample,seeboththeScene
andGameviewssimultaneously.WecoulddraganddroptheGametabbesidethe
Consoletabtoobtainthelayoutdescribedonthenextfigure.
Figure2‑8:ChangingthelayouttodisplaybothGameandSceneviews
Discoveringandnavigatingthroughthescene
Sothatyoucannavigateeasilyinthecurrentscene,severalshortcutsandnavigation
modesareavailable.Thesemakeitpossibletonavigatethroughyourscenejustasyou
wouldinaFirst-PersonShooterortoliterally“Fly”throughyourscene.Youcanalso
zoom-inandzoom-outtofocusonparticularareasorobjects,lookaround(i.e.,using
mouselook)orpantheviewtofocusonaspecificpartofthescene.Themainmodesof
navigationareprovidedinthenexttable;however,wewilllookintotheseinmoredetail
inthenextsectionaswewillbeexperimentingwiththemtoexplore(andmodify)an
existingscene.
Table1:Navigationshortcuts
Navigation
KeyorMouse
Combination
ActivateFlyMode
KeepMRB(Mouse
RightButton)
pressed.
Accelerate
PressShift(inwalk
mode).
Moveinfour
directions(left,
right,forwardand
back)
PressW,A,S,orD.
FloatUpandDown
PressQorE(infly
mode).
Lookaround
PressALTanddrag
themouseleft,right,
forwardorback.
Zoomin/out
Movethemouse
wheel.
Pantheview
PressQ(toactivate
thehandtool)then
draganddropthe
mouse.
Forexample,inthedefaultnavigationmode,youcan“walk”throughthesceneusingthe
arrowkeys(up,down,leftandright).Inthe“flight”mode,whichcanbeactivatedby
pressingandholdingtheMouseRightButton(MRB),wecannavigateusingtheW,A,S
andDkeysandalsolookaroundusbydraggingthemouseinthedirectionwewouldlike
tolook(i.e.,left,right,upanddown)andalsofloatupanddownusingthekeysQandE.
Asyoucansee,bothmodesareveryusefultonavigatethroughyoursceneandto
visualizeallitselements.Inaddition,youcanalsochoosetodisplaythescenealonga
particularaxis(x,y,orz)usingthegizmothatisdisplayedinthetop-rightcornerofthe
Sceneviewasdescribedonthenextfigure.
Figure2‑9:Gizmo
ThegizmoavailableintheSceneviewincludesthreeaxesthatarecolor-coded:x(inred),
y(ingreen)andz(inblue).Byclickingonanyoftheseaxes(orcorrespondingletters),the
scenewillbeseenaccordingly(i.e.,throughthex-,y-,orz-axis).
Ifyouarenotfamiliarwith3Daxes:x,andzusuallyrefertothewidthanddepth,while
yreferstotheheight.Bydefault,inUnity,thez-axisispointingtowardsthescreenif
thex-axisispointingtotherightandthey-axisispointingupwards.Thisisoften
referredasaleft-handedcoordinatesystem.
Alsonotethatbyclickingonthemiddleofthegizmo(whitebox),wecanswitchbetween
isometricandperspectiveviews.
Inadditiontothenavigationtools,Unityalsoofferswaystofocusonaparticularobject
byrotatingaroundaspecificpoint(i.e.,bypressingtheALTkeyanddraggingthemouse
totheleft,right,upordown),ordouble-clickingonanobject(i.e.,intheSceneor
Hierarchyview),sothatthecameraintheSceneviewisfocusedonthisobject(thiscan
alsobeachievedbyselectingtheobjectineithertheSceneorHierarchyviewandpressing
SHIFT+F),orbyzooming-inandout(i.e.,scrollingthemousewheelforwardorback).
WhiletheshortcutsandkeysdescribedinthissectionshouldgetyoustartedwithUnity
andmakeitpossibleforyoutonavigatethroughyoursceneeasily,thereare,obviously,
manymoreshortcutsthatyoucoulduse,butthatwillnotbepresentedinthisbook.
Instead,youmaylookforandfindtheseintheofficialdocumentationthatisavailable
bothoffline(usingthetopmenu:Help|UnityManualthenselectthesectionsUnity
Overview|UnityBasics|LearningtheInterface|SceneView)andonline
(http://docs.unity3d.com/Documentation/Manual/SceneViewNavigation.html).Whenusingthe
documentation,youcanalsosearchforparticularwordsasillustratedonthenextfigure.
Figure2‑10:UsingUnity’smanual
Thehierarchyview
Asindicatedbyitsname,thisviewlistsanddisplaysthenameofallobjectsincludedin
thescene(inalphabeticalorderbydefault)alongwiththetypeofrelationshiporhierarchy
betweenthem.Youmaynoticethatbeforeyouaddanyobjecttothescene,acamerais
alreadypresentinthescenesothatitcanbeviewedintheGameviewthroughitslenses.
Thisviewoffersseveraladvantageswhenweneedtomanageallthesceneobjectsquickly
andperformorganizationalchanges(e.g.,findobjectsbasedontheirname,duplicate
objects,amendobjects’names,amendthepropertiesofseveralobjectssimultaneously,or
changethehierarchybetweenobjects).
Forexample,onthefollowingfigure,wecanseethatthesceneincludesfourobjects:a
cameraandthreecubes.
Figure2‑11:Creatingahierarchybetweenobjects
Wecanalsonoticethatallcubesaregroupedundera“folder”(inUnity,thiscanbe
createdasanemptyobjectinthescene),whichmeansthat:
1.Allthreecubesarechildrenoftheobjectcalledgroup_of_cubes.
2.Theobjectgroup_of_cubesistheparentofthethreecubes.
3.Ifatransformation(i.e.,scaleorrotate)isappliedtotheparent(e.g.,groupofcubes)it
willalsobeappliedtothechildren(i.e.,cube1,cube2,andcube3).
Tochangethehierarchyofthesceneandmakesomeobjectschildrenofaparticular
object,weonlyneedtodragtheseobjectsatoptheparentobject.
Theprojectview
Thisviewincludesanddisplaysallassetsemployedinyourproject(andacrossscenes),
theseinclude:audiofiles,textures,scripts(e.g.,scriptswritteninJavaScript,C#orBoo),
materials,3Dmodels,scenes,orpackages(i.e.,zippedresourcesforUnity).Allthese
assets,oncepresentintheProjectview,canbesharedacrossscenes.
Inotherwords,ifwecreateaprojectandthenascene,andimportassetsforourgame,
theseassetswillbeavailablefromanyotherscenewithinthesameproject.
AsfortheHierarchyview,built-infoldersandsearchcapabilitiesareincludedtoeasethe
managementofallyourassets.
Bydefault,theProjectviewincludestwowindowsdividedvertically(leftandright
columns).Asillustratedonthenextfigure,theleftwindowincludesafoldercalledassets
andaseriesof“smart”folders(i.e.,thecontentofthesefoldersvariesdynamically)called
Favorites.Therightwindowdisplaysthecontentofthefolderselectedontheleft-hand
side.
Figure2‑12:Theprojectview
Inthepreviousfigure,thecontentofthefolderAssetsisdisplayedandconsistsofthe
currentscenelabeledInterface.Byclickingonanyofthesmartfolders(e.g.,All
Materials,AllModels,AllPrefabs,orAllScripts)Unitywillfiltertheassetstodisplay
onlytherelevantonesaccordingly(e.g.,materials,models,prefabs,orscripts).Thiscan
speed-uptheprocessofaccessingspecificassetsandcanbedone(asformanyofthe
functionalitiespresentinUnity)indifferentways.Forexample,youmaynoticeasearch
windowtotheleftoftheProjectviewasillustratedinthenextfigure.
Figure2‑13:Searchingforassetsintheproject
ThesearchwindowintheProjectfoldercanbeusedtosearchassetsbytheirnameorby
theirtype,asillustratedinthenextfigure,byclickingonthisicon
.
Figure2‑14:Filteringthroughtheassetsintheprojectview
Aswecanseeonthepreviousfigure,wehavetheoptiontoselectthetypeofassetsthat
wearelookingfor(e.g.,Texture,Prefab,orScript).Notethatthisoptioncanalsobe
specifiedbytypingt:followedbythetypewearelookingforinthesearchwindow;for
example,bytypingt:materialinthesearchwindow,Unitywillonlydisplayassetsoftype
Material.
Theinspector
Thiswindowdisplaysthepropertiesoftheobjectcurrentlyselected(i.e.,intheSceneor
Hierarchyview)andmakeitpossibletomodifytheattributesaccordingly.Allproperties
arecategorizedinComponents.
Bydefault,allobjectspresentinthescenehaveaname,adefaultlayer(wewilllookat
thisaspectlater)andacomponentcalledTransform.However,itispossibletoadd
componentstoanobjectusingthebuttonAddComponentsorthemenuComponent.
Figure2‑15:TheInspectorwindow
Youmayalsonoticeatickbox,intheInspectorwindow,totheleftofthenameofthe
object,thatcanbeusedtotemporarilydeactivate(andconsequentlyreactivate)the
object.Thiscanbeusefulwhenyouwouldliketotemporarilyremoveanobjectfrom
thescenewithouthavingtorecreateit.
Aswewillseelater,therearemanytypesofcomponentsthatcanbeaddedtoanobjectto
enhanceit,includingphysicsproperties(toenhancehowanobjectwillbehave
realisticallyfollowingthelawsofphysics),rendering(toenhanceitsappearance),or
collision(torefinehowitwilldetectcollisionswithotherobjects).Forexample,the
defaultcomponentTransformincludestheposition,rotationandscaleoftheobject
selected.
Theattributestag,layerandstatic,whileimportant,willbecoveredinlatersections.
Aswewillseelater,ascenecanbeeditedandplayed.However,ifwetrytomodifythe
attributesofanobjectwhilethegameisplaying,thesewillnotbesaved.Inotherwords
formodificationstobesavedinthescene,theyhavetobemadewhilethegameis
stopped(i.e.,notplayed).
Theconsoleview
Asseenpreviously,theconsolewindowwilldisplaymessages,fromUnity,relatedto
possibleerrorsandwarningsinyourcodethatmaypreventthegamefromplaying,or
messagesthatyoucanprintthroughyourowncode(e.g.,fordebuggingpurposes).
Theassetstorewindow
Thiswindow,whichisnotdisplayedbydefault,connectsyoutotheAssetStore,anonline
repositoryandmarketplacewhereyoucansearchforandfindassetsforyourgame;some
ofthemarefreeandsomeotherarepremium.Thiswindowcanbeaccessedthroughthe
mainmenu(i.e.,Window|AssetStore)orbyusingthecorrespondingshortcut(CTRL+9).
Figure2‑16:TheAssetStoreview
NavigatingthroughtheVikingVillage
WhilewehavelookedatthemainwindowsavailableinUnity,wewillnowbecome
familiarwithnavigatingthroughasceneusingtheprojectVikingVillage.
Thisprojectisrelativelyheavy(841MB),soifyourbroadbandconnectionorthespace
availableonyourharddrivearelimited,youmay,insteadofdownloadingtheproject,
justreadthroughthissection,orskiptothenextsection(levelroundup),asmanyofthe
shortcutsdemonstratedinthissectionwillbecoveredagainlaterinthisbook.
YoucandownloadthisprojectthroughtheAssetStorewindowasfollows:
OpentheAssetStorewindow(CTRL+9).
Typethetext“Vikingvillageunityessentials”inthesearchwindow(i.e.,top-right
corner).
Thisshouldreturnoneresult.
Figure2‑17:AccessingtheAssetStore
Selecttheresult(i.e.,VikingVillage),thisshoulddisplaythefollowingwindow:
Figure2‑18:DownloadingtheVikingVillageproject
PressthebuttonlabeledDownload.Asyoupressthisbutton,Unitywillaskyoutologin
usingtheemailandpasswordprovidedearlier.
Onceyouhaveenteredthesedetailsandloggedin,wecanpresstheDownloadbutton
again.
TheDownloadbuttonshouldnowbereplacedbyaprogressbarastheprojectis
downloading.
Whentheprojectisdownloaded,youcanclickontheImportbutton.
Figure2‑19:ImportingtheVikingVillageproject
AwindowlabeledImportingPackageswillappear.
ClickonthebuttonImport.
Onceyouhaveimportedthisproject,wecannowdothefollowing:
IntheProjectwindow,lookforallscenesavailableintheprojectbyenteringthe
keywords“t:scene”andpresstheReturnkey;thisshoulddisplayonescene,asdescribed
inthenextfigure.
Figure2‑20:ScenesavailableintheVikingvillageproject
Wecanthendouble-clickonthescenelabeledThe_Viking_Villageanditshould
openaccordingly.
Whenthesceneisopenyoumayneedtozoom-in(i.e.,usingthemousewheelor
ALT+CTRL+draganddrop)withintheScenewindow.
Onceyouhavezoomed-inenough,youshouldseeanoverviewoftheVikingvillage,as
illustratedonthenextscreenshot.
Figure21:TheVikingvillagefromadistance
YoumaypantheviewtolookaroundbypressingQonthekeyboard,thentheAltkey
andbydragginganddroppingthemousewithintheSceneview.
Atthisstagewecanseethatthisisarathercomplexmodel,andwewillonlyfocuson
theplayerforthetimebeing.
Todoso,let’slookattheHierarchywindowandenterthekeywordflyinginthesearch
window;thisshouldreturntworesultsasfollows:
Figure2‑22:Objects’hierarchyintheVikingvillagescene
Let’sfocustheviewontheplayerbydouble-clickingontheobjectlabeled
FlyingRigidbodyFPSController_LowQualityintheHierarchyview.Theviewshouldnow
lookasfollows:
Figure2‑23:NavigatingtheVikingvillagescene(focusingontheplayer)
Theplayer(ormaincamera)isnowinthecenteroftheview.Toseeitmoreclearly,we
canzoom-in(mousewheelorCTRL+draganddrop)andlookatitfromdifferentangles
(ALT+draganddrop).
Onceyoufeelconfortablewiththesecontrols(i.e.,zoomingandrotatingaroundobjects),
youcannavigatethroughthesceneanduseothershortcutsasfollows:
Navigatethesceneusingsomeoftheshortcutsandnavigationmodesdescribedearlier
(e.g.,walkorfly).
SwitchfromtheWASDmodetotheFlyMode(i.e.,RightMouseButtonpressed).
Selectsomeoftheobjectspresentinthescene(i.e.,clickonceortwiceonthese)and
inspecttheirattributesintheInspectorwindow.
Trytolookatthescenefromdifferentaxes(i.e.,x,y,andz)byclickingononeofthe
armsorlabelsoftheGizmo.
Notethatifyouwishtoundoanaction(e.g.,movingorresizinganobject)youcando
sobypressingCTRL+Z,asyouwoulddoinmostsoftwareorbyselectingEdit|Undo.
Onceyoufeelconfortablewiththisnavigation,itistimetoplaythescenebypressing
eitherCTRL+PorbyclickingonthePlaybutton,ablacktrianglelocatedatthetopofthe
window.
Notethatyoucanmaximizethewindowifneedbe,sothatitoccupiestheentirescreen,
eitherbeforethegamestartsorduringplay.Thismakesitpossibletoviewyourgame
moreclearly.
Tomaximizethewindowonlywhenthegame/sceneisplayed,youcanclickonthetab
labeledMaximizeonPlaylocatedatthetoprightcornerofthewindow(thiscanbe
cancelledbyclickingagainonthesametab).
Tominimize/maximizethewindowatanyothertime,youcansimplyclickonthelist
locatedinthetoprightcornerofthewindow.
LevelRoundup
Summary
Inthischapter,wehavebecomefamiliarwiththedifferentviewsandwindowsavailable
inUnity.Wealsolookedathowtonavigatethroughscenesandhowtochangethelayout
ofourworkingenvironment.Inthenextchapter,wewillharnesstheseskillstobeableto
createourown3Denvironment.
Quiz
Itisnowtimetotestyourknowledge.Pleaseanswerthefollowingquestions(e.g.,Yesor
No).Theanswersareavailableonthecompanionwebsite
(http://www.learntocreategames.com/learn-unity-ebook).Youdon’tneedtohavedownloadedthe
VikingVillageprojecttobeabletoanswerthesequestions.
1.TheshortcuttoopentheConsolewindowisCTRL+1.
2.TheshortcuttoopentheProjectwindowisCTRL+2.
3.TheVikingVillageprojectwascreatedforUnity5.
4.TheConsolewindowcandisplayalltheobjectsincludedinyourscene.
5.TheProjectwindowcandisplaymessagesorerrorsfromyourcode.
6.Onceanassethasbeendownloadedinthescene,itisnotavailableinotherscenes
withinthesameproject.
7.Onceanobjecthasbeendeactivated(i.e.,usingthetickboxintheInspector)itwillbe
deletedfromyourprojectforever.
8.Tomakesomeobjectschildrenofotherobjects,youcanselecttheoption:GameObject
|CreateChild.
9.Unityisusingaright-handcoordinatesystem.
10.HelponUnityisonlyavailableonline(i.e.,youneedtobeconnectedtotheInternetto
accessit).
Checklist
Ifyoucandothefollowing,thenyouarereadytogoto
thenextchapter:
Navigatethroughasceneeasily.
UnderstandtheroleoftheInspector,Game,andScene
views.
Selectanobjectinthehierarchyandzoom-inifneed
beintheSceneview.
Selectanobjectandlookatitspropertiesinthe
Inspectorwindow.
Answeratleast7outof10ofthequestionscorrectly
inthequiz.
3
CreatingandExportingyourFirstScene
Inthischapter,wewillcreateourfirstscene,andstarttoinclude,combine,andtexture
basicshapessuchasboxes.Thischapterexplainshowtousebasictransformationsand
applythemtoobjects.Itwillalsoexplainhowtomanageandgroupobjects.
Aftercompletingthissection,youshouldbeableto:
Createascene.
Addbasicobjects.
Createandapplycolorsandtexturestoobjects.
AddaFirst-andaThird-PersonControllerandexploreyourscene.
Groupshapes.
Searchforparticularobjectsorassetsusingshortcuts.
Exportyourfirstscene.
Creatinganewprojectandanewscene
Nowthatwehavecoveredthemainfeaturesfortheinterface,wewillcreateanewproject
withasimplegamewheretheplayerhastojumponseveralboxeswithoutfalling.Itwill
beusingsimplebuilt-inobjectsandstandardassets(i.e.,aFirst-PersonController)aswell
astexturesandcolorsforsomeoftheseobjects.
Aftercompletingthissectionyouwillbeableto:
Addbasicobjectstoyourscene.
Applybasictexturingandcoloringtoobjects.
Transformobjects(i.e.,move,scaleandrotate).
Addacharactercontrollertothescenetobeabletowalkaroundthelevel.
Addandconfigurelights.
Groupobjectsandapplyattributestoseveralobjectsatatime.
First,let’screateanewprojectandscene:
SelectFile|NewProjectandspecifyanewnameandlocationforthisnewproject.
Onceyournewprojecthasbeencreated,selectFile|NewScenetoopenanewscene.
Thisshouldopenanewscene.
Atthisstage,wehaveablankcanvaswherewecanstarttoaddobjectsandbuildour
game.
Addingandcombiningsimplebuilt-inobjectstoyourscene
Aswewillseelateron,wecancreateourgameenvironmentusingawiderangeof
primitiveshapes(e.g.,cylinders,spheres,boxes,etc.),lights(e.g.,directionallightsor
pointlights),camerasandotherbuilt-inassets(e.g.,charactercontrollers).Oncethese
objectshavebeenaddedtothecurrentscene,Unitymakesitpossibletomodifytheir
attributes.
Asweopenthenewscene,youwillseethat,bydefault,thesceneincludesacamerathat
iscalledMainCamera.Thiswillbethecaseforanynewscene,andwewillbeableto
eitherdeletethiscameraormodifyitsproperties(e.g.,locationororientation)atalater
stage.
IfyouclickonthiscameraintheHierarchyview,youshouldbeabletoseeasmall
windowlabeledCameraPreviewinthebottom-rightcorneroftheSceneview.This
previewwindowrepresentsthesceneviewedthroughthelensesofthecamera.
Figure3‑1:Defaultcameraforanewscene
Thisishowyourgamewillbeviewed.Atthemoment,wecanonlyseeabluescreen
withinthepreview(locatedinthebottom-rightcorneroftheSceneview),asnoobjectsor
lightshaveyetbeenaddedtothescene.WecanalsoseethattheInspectorwindow,thatis
locatedtotherightofthescreen,displaystheattributesofthiscamera.Amongstother
things,weseethatitislocatedattheposition(x=0,y=1,z=-10)andthatithasnotbeen
rotatedyet.Finally,ifwelookattheSceneview,wecanseethreearrowsfromtheobject:
onered(alongthex-axis),onegreen(alongthey-axis)andthelastoneblue(alongthezaxis).
IfyouclickontheGametab,youwillalsoseeabluescreen(asdisplayedinthe
camerapreview).
Figure3‑2:Blankgameviewforanewscene
Firstlet’screateacubethatwillserveastheground:
SwitchbacktotheSceneview(i.e.,clickonthecorrespondingtab).
Select:GameObject|3DObject|Cube,fromthetopmenu.
Thiswillcreateaboxthatwillbe,bydefault,locatedat(0,0,0)withasizeof1.This
meansthattheheight,depth,andwidthofthisobjectareequalto1.
RenamethecubemyCube:torenamethecube,wecan(1)selectitintheHierarchy
windowandthenpressCTRL+ENTERsimultaneously,(2)selectitintheHierarchy
windowandleft-clickonceonit,or(3)right-clickontheobjectintheHierarchywindow
andselectRenamefromthecontextualmenu.
Onceyouhaverenamedthecube,wecanchangesomeofitspropertiesandseehowit
affectsitsappearance.Forexample:
IntheInspectorwindow,changethex,y,andzscalepropertiesto2andseehowit
affectsthesizeofthecube.
Changeitsyrotationattributesto45(i.e.,arotationaroundthey-axisexpressedin
degrees),andseehowitsorientationhaschanged.Notethatforanyoftheseparameters,
youcaneitherchangethevalueinthecorrespondingtextfields,orclickononeofthe
parametersanddraganddropthemouse:thiswilleitherincreaseordecreasethevaluein
thecorrespondingfield.Itisusuallyaneasierwaytoamendanobject’sattributes.
Onceyouarecomfortablewithmodifyingthetransformpropertiesofthecubeusingthe
Inspector,let’slookatotherinterestingwaystoobservetheobjectsandthesceneto
modifytheirattributes.
Youwillnoticeatoolbarlocatedinthetop-leftcornerofthewindow,asillustratedonthe
nextfigure.
Figure3‑3:Toolbar
Thistoolbarincludesfivedistinctbuttonsthatareshortcutsto(fromlefttoright)(1)
modifytheviewmode(e.g.,pan,orrotatetheview),(2)movetheobjectcurrently
selected,(3)rotatetheobjectcurrentlyselected,(4)scaletheobjectcurrentlyselected,and
(5)bothmoveandscaletheobjectcurrentlyselected.Thesefivebuttonscanalsobe
accessedusingthekeyshortcutsQ,W,E,RandT.
Lets’experimentwiththepanningtool:
Selectthepanningtoolfromthetoolbar(i.e.,choosethefirsticonfromtheleft,orpress
thekeyQ).
Youshouldseethatthemousecursorturnsintoahand.
Draganddropthemouseinthescreenview:youshouldseethatyoueffectivelypanthe
view.
Now,lets’experimentwiththeMovetool:
SelecttheMovetoolfromthetoolbarorusethecorrespondingshortcut(W).
Youshouldnowseethreearrowsfromthecube.Thesearrowsarehandlesthatyoucan
draganddroptomovetheselectedobjectinaparticulardirection(e.g.,alongthex-,y-or
z-axis).
Aswesuccessivelydragtheblue,redandgreenhandles,observehowthesemoveyour
objectalongthecorrespondingaxes.
Beforewelookatthethreelastmodes,let’slookatausefulwidgetcalledagizmo.This
widget,asillustratedonthenextfigure,islocatedinthetop-rightcorneroftheScene
viewandmakesitpossibletoviewthescenefromseveralaxesandperspectives.
Figure3‑4:Usingthegizmo
Usingthisgizmo,andbyclickingonitsx,y,orzarms,wecanseethescenefromthe
correspondingaxis.Let’sexperimentwithit:
Wecansuccessivelyclickonthex,y,andzarmsofthegizmo,andseehowtheview
changes.
Notethatbyclickingonthemiddleofthegizmo,wecanresettheviewtoitsinitialstate
(i.e.,x-axispointingtotheright,y-axispointingupwards,andz-axispointingoutwards).
Toreadjusttheview,wecanalsousetheALTkeyanddraganddropthemouse,sothat
wecanrotatearoundtheobjectaccordingly.
Afterthisshortdistraction,let’scomebacktoourtop-lefttoolbarandexperimentwiththe
threeremainingbuttons.
Now,lets’experimentwiththeRotationtool:
SelecttheRotationtoolfromthetoolbar(thirdiconfromtheleft)orusethe
correspondingshortcut(E).
Youshouldnowseeacombinationofgreen,red,andbluecirclesaroundtheobject.These
arehandlesthatyoucandraganddroptorotatetheobjectcurrentlyselectedarounda
particularaxis(e.g.,aroundthex-,y-andz-axis).
Figure3‑5:Rotatinganobject
Thecolorofthehandleindicatestheaxisaroundwhichtheobjectwillberotated.For
example,bydragginganddroppingthegreenhandle,wecanrotatetheobjectaround
they-axis.Thesameappliestotheblue(aroundthez-axis)andred(aroundthex-axis)
handles.
Aswedragthesehandles,wecanseethatthevaluesforthecorrespondingrotationinthe
Inspectoralsochange.
Figure3‑6:Rotatinganobjectaroundthey-axis
Now,lets’experimentwiththeScaletool:
SelecttheScaletoolfromthetoolbar(fourthiconfromtheleft)orusethecorresponding
shortcut(R).
Youshouldnowseeacombinationofgreen,red,andbluelinesandhandlesaroundthe
object.Thesearehandlesthatyoucandraganddroptoscaletheselectedobjectalonga
particularaxis(e.g.,alongthex-,y-andz-axis).
Figure3‑7:Scalinganobject
Thecolorofthehandleindicatestheaxisalongwhichtheobjectwillberotated.For
example,bydragginganddroppingthegreenhandle,wecanscaletheobjectalongthe
y-axis.Thesameappliestotheblue(z-axis)andred(x-axis)handles.Alsonotethatby
draggingthemiddlewhitesquare,thetransformationwillbeuniform.Inotherwords,
theamountofscalingwillbethesameonallthreeaxes(x-,y,andz-axis).
Atthisstage,wehaveperformedseveraltransformationsonthenewcube,andwemay
wanttoresetitsattributessothatitisthesameaswhenitwasinitiallycreated.Wecando
sobyusingthecogwheellocatedinthetop-rightcornerofthetransformattributesofthe
cube,asdescribedonthenextfigure.
Figure3‑8:Resettingtheattributesofanobject
ThelastitemonthetoolbaristheRecttool.ItcombinestheMoveandScaletools.Once
youhaveselectedtheRecttool,youcanmovetheobjectbydragginganddroppingthe
mouse,ormodifytheobject’swidth,height,anddepthbydragginganddroppingthe
correspondinghandles.
FormoreinformationandtipsonhowtouseUnity’sinterface,youcanvisit:
http://docs.unity3d.com/Manual/LearningtheInterface.html
Addingcolorsandtextures
Atthisstagewehaveabox,acamera,andalsoalightinourscene.Notethat,whilethe
lighthasbeencreatedbydefault,wecouldhaveaddedlighttooursceneusingthemenu:
GameObject|Light|DirectionalLight.
Let’srenamethelightpresentinoursceneaswehavedonebefore(e.g.,right-clickon
theobjectintheHierarchyview)andrenameitmyLight.
Oncethisisdone,wewillchangetheorientationandpositionofthelightsothatitis
abovethecubeandpointingdownwards.
Todoso,wecanstartbyresettingthetransformattributesofthelightbyusingthe
associatedcogwheellocatedatthetop-rightcorneroftheInspector.
AsweresettheTransformattributesofthelight,weseethatallitsparametersaresetto
0.
Wecannowmovethelightalongthey-axissothatitisabovethecube(e.g.,by
switchingtotheMovemode).
Wecanalsorotatethelight90degreesaroundthex-axisusingtheInspector.
Ifweusethegizmotoseethescenealongthex-axis,wecanclearlyseethatthelightis
effectivelypointingdownwards.
Figure3‑9:Rotatingthelightaroundthex-axis
Onceyouarehappywiththepositionofthelight,youcanrotatearoundthisobjectusing
ALT+draganddrop,andalsolookatthescenefromtheGameview.
Atthisstage,ourlightisset-upaswellasthecube;however,wewouldlikethe
camerapresentinourscenetolookatthecubefromabove.Wewill,accordingly,change
theattributesofthecameratoimplementthisfeatureusingtheInspector.Notethat,we
couldalsoaddmultiplecamerastothescene,anddisplaytheimagecapturedbythesein
differentareasofthescreen,andwewillseethisfeaturelaterinthisbook.
SelectthecameraintheHierarchyview,asdescribedonthenextfigure.
Figure3‑10:Selectingthedefaultcamera
Sothatitisabovethecubeandpointingdownwards,let’schangeitstransformsettingsas
follows:
Position:(0,4,0):weraisethecamerafourmetersabovetheground.
Rotation:(90,0,0):werotatethecamera90degreesaroundthex-axis.
Oncethesechangeshavebeenmade,thesceneshouldlookasillustratedonthenext
figure.Youmaynoticethat,intheSceneview,thecameraobjectissymbolizedbya
camera,andthatitsfieldofviewissymbolizedbywhatlookslikeaprism,which
encompassesthecubeinourscene.Thismeansthatthecubeisinthefieldofviewofthe
camera.Wecancheckthisinthecamerapreviewwindowlocatedinthebottom-right
corneroftheSceneview.
Figure3‑11:Displayingthefieldofviewofthecamera
Oncethecamerahasbeensetup,let’smodifytheattributesofthelight.Wewillessentially
changethecolorofthelightaswellasitsintensity,sothatyoucanseehowthesecanbe
amended:
SelectthelightintheHierarchywindow.
IntheInspector,youmaynoticeacomponentcalledLight,whichincludesallthe
attributes(exceptfortheTransformattributes)ofthelight.Clickonthewhiterectangleto
therightofthelabelColor.Thiswillmakeitpossibletomodifythecolorofthelight.This
maybeusefulwhenyouneedtosettheatmosphereinyourgameandaddlightsof
differentcolors.
Onceyouhaveclickedonthisrectangle,awindowlabeledColorappears.Thiswindow
issimilartotheoneusedinimagemanipulationsoftware,suchasGimporPhotoshop,
wherebyyoucanpickordefineacolorbasedonitsRGBcode.
ForthosenotfamiliarwiththeRGBcode,itsstandsforRed,Green,andBlueanditcan
beperceivedasapalettewherewespecifytheamountofred,green,andbluethatwill
beusedtocreateanewcolor.Inthiswindow,theamountofeachcolorisanumber
between0and255.Whichmeansthatifweuse(R=255,G=0,B=0)wewillobtainred.
Ifweclickinsidethecolorwindow,andchooseacolor,wecanseehowtheRGB
componentschangeaccordingly.Forthetimebeing,choseacolorofyourchoice,for
examplealightblue.
YoumayalsonoticeanAlphaattribute(A)belowtheamountofblue.Thisisusually
usedtospecifyhowtransparentacolorwillbe(255meanstotallyopaqueand0means
totallytransparent).
Figure3‑12:Changingthecolorofthelight
Onceyouhavechangedthecolorofthelight,youshouldseethatthecoloroftheboxwill
beblue;thesamewillapplyifweswitchtotheGameview.
Creatingthegroundfromabox
Sofarwehaveacube,acameraanda(slightlyblue)lightinourscene.However,we
wouldliketobuildascenewhereacharacterwalksonthegroundandpossiblyjumps
fromboxestoboxesorwalksupthestairs.Thefirststepincreatingthisenvironmentwill
betosettheground.Tocreatetheground,wecanrecycletheboxthatwehavealready
createdbymodifyingbothitssizeandappearance:
SelecttheboxlabeledmyCube.
Changeitsscalepropertiesto(40,1,40).Thismeansthatwescaleitonthex-andzaxesby40.
RenamethisboxgroundusingtheHierarchywindowortheInspector(toptextfield).
Figure3‑13:Creatingthegroundfromtheinitialbox
Nowthatwehaveresizedandrenamedtheground,itwouldbegreattoaddsometexture
tomakeitlookabitmorerealistic.Forthis,wewillimportatextureassetandapplyitto
theground.
Youmaydownloadagroundtextureofyourchoiceordownloadandusetheoneprovided
onthecompanionwebsite.Forthisscene,Ihavesavedatextureonmydesktopinafolder
calledunity_assets.
InUnity,let’simportandapplythistextureasfollows:
SelectAsset|ImportNewAsset…:thiswillopenawindowthatmakesitpossibleto
importassetsinyourproject.Thesecanbeimages,audio,or3Dmodels.Notethatassets
canbeusedacrossscenes,soweonlyneedtoimportthemonceinourproject,andyou
canthenreusetheminallscenethatarepartofthesameproject.
AwindowlabeledImportNewAssetshouldappear,asillustratedonthenextfigure.
Youcanthenselectthefolderwheretheimagesthatyouhavedownloadedfromthe
companionwebsiteweresavedandunzipped,selecttherelevanttexture(i.e.,tile.jpg),
and,finally,clickonImporttoimportthisasset.
Figure3‑14:Importinganimageassetintotheproject
Toseewherethisassethasbeenimported,let’sclickontheProjecttab:
Aswecanseeonthenextfigure,thisimagehasbeenimportedautomaticallyinsidethe
Assetsfolderwithintheproject.
Figure3‑15:Locatingtheimportedasset
NotethatwecouldcreateanewFolder(Create|NewFolder)toorganizeourassetsand
movethisimagetothenewfolderaccordingly.
Toapplythistiletotheground,wejustneedtodraganddropthisimagefromtheAssets
folderontothegroundobjectintheSceneortheHierarchyview.
Figure3‑16:Applyingatexturetothegroundobject
Asweapplythetexture,youmaynoticethatthetilingofthetexture,whichmeansthe
numberoftimesthistextureisrepeatedonthesurfaceoftheobject,couldbeimproved.
Atpresent,basedonthegridlines,weseethattheyareonemeterapart.
However,wecanchangethissettingeasilyusingthecorrespondingmaterial.Inother
words,wheneveratextureisimportedandappliedtoanobject,acorresponding
materialiscreated,andmakesitpossibletomodifyhowthistexturewillbeusedand
perceived(i.e.,howitwillberendered).Thismaterialislocatedinsideafoldercalled
Materials,whichisusuallyinthesamefolderasthetexture.Forexample,ifthetexture
wasimportedinthefolderAssetsthenthecorrespondingmaterialwouldbesavedinthe
folderAssets|Materials.Again,ifyoudecidedtocreateanewfolder(forexample,
Assets|myAssets)andimportthistextureinthisfolder,thenthecorrespondingmaterial
wouldbelocatedinAssets|myAssets|Materials.
IfweopenthefolderlabeledMaterials,wecanfindamaterialcalledtile.Asweclickon
thismaterial,wecanseeseveralofitsproperties,includingMainColor,TilingandOffset,
asillustratedonthenextfigure.
Figure3‑17:Displayingtheattributesofanewmaterial
Fornow,wewillonlychangethexandytilingpropertiesfrom0to10.Thisindicates
thatthetexturewillberepeated10timesonthex-andy-axes.
Aftermakingthesemodifications,wecanzoom-intolookatthegroundfromacloser
range(ALT+CTRL+draganddroporusethemousewheel).
Figure3‑18:Increasingthexandytilingattributes
Youmayalsonoticeasphere,inthebottom-rightcornerofthescreen,whichprovidesan
indicationofhowthetextureandmaterialwilllooklikeinthegame.Wecanalsolookat
thescenefromthegamewindow.
Addingmulticolourboxesandstairs
Beforeweaddnewobjectstothescene,let’smodifytheattributesofthelightslightly,so
thatitilluminatesthescene:
SelectthelightlabeledmyLight.
Changeitsintensityto.96usingtheInspectorwindow.
Changeitsypositionto8.
Oncethisisdone,wewilladdasuccessionofboxesusingessentiallyduplications,to
speed-uptheprocess:
Createanewcube(GameObject|3DObject|Cube).
RenamethiscuberedCube(e.g.,intheHierarchywindoworintheInspector).
Changetheycoordinate(position)ofthiscubesothatitisabovetheground;for
example,youcanusetheposition(0,1,0).
Wewillnowaddacolortothiscube,usingasimilarprocessasforthegroundtexture:
IntheProjectwindow,openthefolderAssetsandthenselectthefolderlabeled
Materials.
IntheProjectwindow,youmaynoticeamenulabeledCreatelocatedinthetop-left
cornerofthisProjectwindow.Thismenumakesitpossibletocreatedifferenttypesof
assetsforyourproject,includingmaterials.
IntheProjectwindow,selectCreate|Material:thiswillcreateanewmaterialassetin
thisfolder.
RenamethismaterialredColorandselectit(i.e.,clickonceonit).
Makesurethatthismaterialisselected.
IntheInspectorwindow,clickonthewhiterectangleofthelabelAlbedo(orMaincolor
inpreviousversionofUnity)todefineacolorforthismaterial.
Asthecolorwindowappears,selectaredcolor.
Figure3‑19:Creatinganewcolorforthecube
Oncethisisdone,wejustneedtodraganddropthisnewmaterialontothecube(inthe
SceneorHierarchyview).
Ifwezoom-intolookattheobjectlabeledredBoxindetail,wecanseethattheredcolor
hasbeenappliedtoallsidesofthecube.
Nowthatwehavecreatedourfirstcoloredcube,wecancreatesimilarcubesusing
successiveduplicationstospeed-uptheprocess:
IntheHierarchywindow,selecttheobjectlabeledredCube.
Duplicatethisobject:wecanright-clickonthisobjectandselectDuplicatefromthe
contextualmenuorpressCTRL+D.
Wecanthenrenamethenewcube(i.e.,theduplicatedobject)greenCube,andmoveit
alongthex-axis(i.e.,usingtheredhandle).
Figure3‑20:Addinganewcubeusingduplication
Asfortheprevioussection,wewillcreateanewgreencolor:
IntheProjectwindow,openthefolderAssetsandselectthefolderlabeledMaterials.
SelectCreate|Material:thiswillcreateanewMaterialassetinthisfolder.
RenamethismaterialgreenColorandselectit(i.e.,clickonceonit).
Setthecolorofthismaterialtogreen.
OncethisnewgreenColormaterialhasbeencreated,wecanapplyittothesecondcube
andwecancheckthatthecolorhasbeeneffectivelyappliedtoallsidesofthiscubeby
lookingaroundit(bypressingALTanddraggingthemouse).
Figure3‑21:Duplicatingtheinitialcube
Wecan,again,duplicatethisgreencube,renamethisduplicategreenCube2andmoveit
alongthex-axis.
Addingafirst-personcontroller
Atthisstage,wehavearelativelybasicscenewithafewcoloredandtexturedboxes(i.e.,
fortheground),alight,andacamera.Wewill,inthenextsection,importacharacter
controllerthatwewillusetonavigatethroughthescene.Thisbuilt-inelementincludesall
thenecessaryfeaturestosimulatethemovementofacharacterinathree-dimensional
environment(e.g.,walking,running,jumping,orlookingaround)
SelectAssets|ImportPackage:youwillseealistofassetsthatcanbeimportedinyour
project.Theseassetsarenotimportedbydefault,andyoucanpickandchoosewhichone
youwillimportbasedonyourneeds.Fornow,wewillchoosetheassetcalledCharacters.
SelectCharactersfromthelist(orCharacterControllersifyouareusinganearlier
versionofUnity).
Afterafewseconds,anewwindowlabeledImportingPackageswillappear.
Figure3‑22:Importingcharactercontrollers
Ifyouscrolldown,youmaynoticethatthispackageincludesacombinationofobjects,
sounds,andscripts.Youmayalsonoticetickboxestotheleftoftheseobjects.This
indicatesthatyoucanimportselectively.Inotherwords,youcandecidewhichelement
youwishtoimportinyourproject.
Fornow,aswewillimportthefullpackage,wewillleavealltheseboxestickedandclick
onthebuttonImport.
Afterafewseconds,theimportshouldbecomplete.
Theseassets,whichareimportedaspartofthepackage,areusuallysavedinthefolder
labeledStandardAssets>Characters(orStandardAssets>CharacterControllersifyou
areusingapreviousversionofUnity).
Ifyouopenthisfolder,wecannoticethatitincludesassetsforboththeFirst-Person
Controller(viewfromtheeyesofthemaincharacter)andtheThird-PersonController
(viewfromthecameralocatedbehindthemaincharacter).
Nowthatwehaveimportedtherelevantpackage,let’suseoneofthecharactercontrollers
tonavigatethroughourscene:
IfyouareusingUnity5:locatethefolderAssets>StandardAssets>Characters>First
PersonCharacter>PrefabsanddraganddroptheiconlabeledFPSControllerontothe
scene.
Figure3‑23:AddingtheFirst-PersonControllerinUnity5
IfyouareusingapreviousversionofUnity(e.g.,4.5):locatethefolderAssets>Standard
Assets>CharacterControllersanddraganddroptheiconlabeledFirst-PersonController
tothescene.
Figure3‑24:AddingaFirst-PersonControllerinUnity4.x
OncethisisdonewecanmovetheFPScontrollerabovethegroundintheSceneview
andcheckhowthegamelookslikeintheGameview.
Wewillalsodeactivatethemaincamera,aswedon’tneeditanymorebecausetheFPS
controllerincludesitsowncamera.Todoso,wejustneedtoselecttheobjectlabeled
MainCameraintheHierarchyview,and,usingtheInspector,deselecttheboxtotheleft
ofthelabelMainCamera.
Aftermakingthesemodifications,itistimetotestthescenebypressingthePlaybutton
(theleft-mosttrianglelocatedatthetopofthewindow,asillustratedonthenextfigure)
oralternativelybypressingtheshortcutCTRL+P.
Figure25:Buttonstocontrol(play)thescene
Asweplaythescene,wecannavigateusingthearrowkeysfromthekeyboard,wecan
jump(usingthespacekey),lookaroundusingthemouse,orrunbypressingthearrowkey
whilealsopressingtheSHIFTkey.
Figure3‑26:Navigatingthroughthescene
NotethatyoucanswitchbetweenGameandSceneviews,asthegameisplaying,tolook
attheattributesofallobjectsinthescene.Wecouldalso,forexampledisplaybothviews
simultaneouslybydraggingtheGameviewinthelowerpartofthescreen,asillustrated
onthenextfigure.
Figure3‑27:Displayingboththesceneandthegameviewssimultaneously
Addingathird-personcontroller
Aswehaveseenintheprevioussection,Unityoffersseveraltypesofcharactercontrollers
tonavigatethescene.WhilewehaveexperimentedwiththeFirst-PersonController,it
wouldbegreattoseehowthesecondtype(i.e.,Third-PersonController)works.
ToaddaThird-PersonController,theprocesswillbesimilartotheonewehavefollowed
sofar,aswewilladdacorrespondingprefab(e.g.,astandardasset)tothescene.
IfyouareusingUnity5:locatethefolderAssets>StandardAssets>Characters>
ThirdPersonCharacter>PrefabsanddraganddroptheiconlabeledThirdPersonController
tothescene.
Figure3‑28:AddingtheThird-PersonControllerinUnity5
IfyouareusingapreviousversionofUnity(e.g.,4.5):locatethefolderAssets>Standard
Assets>CharacterControllersanddraganddroptheiconlabeled3rdPersonControllerto
thescene.
Figure3‑29:AddingaFirstpersonControllerinUnity4.x
Thisshouldcreateanewobjectlabeled3rd-PersonControllerintheSceneview.
Oncethisisdone,wecanmovethe3rd-PersonControllerabovethegroundintheScene
viewandcheckhowthegamelookslikeintheGameview.
Beforedoingso,wewilldeactivatetheFirst-PersonControllerthatwehaveincluded
previously,toavoidanyconfusionbetweencameras.Todosowejustneedtoselectthe
First-PersonControllerintheHierarchyview,and,usingtheInspector,deselecttheboxto
theleftofitslabel.
IfyouareusingUnity4.x,youareprettymuchreadytogoandyoucanplaythescene.
However,ifyouareusingUnity5.x,thereareafewmorethingsweneedtodoinorderto
seeourcharacter.
Asitis,ournewcharacter,whileitwillbeabletomoveinalldirections,willnotbe
displayedonscreen,asthereisnocamerasetupyetittofollowthecharacter.Todoso,we
needtoimportapackagethatincludescamerasthathavetheabilitytofollowaspecific
target.Inourcase,wewouldlikeittofollowthecharacter.Thankfully,Unityincludes
assetsthatarepartofthepackagecalledCamera,whichcandojustthat.Let’simportone
ofthesecamerasanduseittofollowourcharacter:
Fromthetopmenu,select:Assets|importPackage|Cameras.
Anewwindowshouldappearthatdescribesalltheassets(e.g.,scriptsandobjects)
includedinthispackage.Aswewillbeimportingallofthese,clickImport.
Afterafewseconds,thepackageshouldbeimported.Itscontentwillbelocatedinthe
folderAssets>StandardAssets>Cameras.
IntheProjectwindow,locatethefolderAssets>StandardAssets>Cameras>Prefabs
asdescribedonthenextfigure.
Figure3‑30:Importingcameraassets
Asyoucansee,thisfolderincludesfourcameratypes.Fornow,wewillbeusingthe
cameraprefabcalledMultipurposeCameraRig.Thistypeofcameracanbeusedtofollow
aparticulartarget.
NotethatwhiletheprefabFreeLookCameraRigwillfollowanobject,the
MultipurposeCameraRig,whenusedwiththeplayer,willensurethatthecamerais
alwaysrotatingsothatitadjuststotheplayer’sdirection(e.g.,behindtheplayerand
facingforward).
DraganddropthecameraprefablabeledMultipurposeCameraRigtotheSceneview.
Selectthisobject(i.e.,thecamera)intheHierarchyview,asdescribedinthenextfigure.
Figure3‑31:Addingthecameratothescene
Asyouhaveaddedthecameratothescene,youmaynotice,lookingattheInspectorview,
acomponentcalledAutoCam(Script).Withinthiscomponent,youmayseeanattribute
calledTargetthatiscurrentlyempty.Thisfieldreferstotheobjectthatwewanttotrack
withthecamera.SototracktheThird-PersonController,wewillneedtodraganddropit
fromtheHierarchyviewtothisfield(i.e.,Target)asillustratedonthenextfigure.
Figure3‑32:Settingthetargetforthecamera
Aftermakingthesemodifications,itistimetotestthescenebypressingthePlaybuttonor
alternativelyusingtheshortcutCTRL+P(orAPPLE+PforMacusers).Beforeyouplay
thescene,justmakesurethatboththeFirst-PersonControllerandtheMainCameraare
deactivated.
Asweplaythescene,wecannavigateusingthearrowkeysfromthekeyboard,wecan
jump(usingtheSPACEkey),lookaroundusingthemouse,orrunbypressingthearrow
keysonthekeyboard,whilealsopressingtheSHIFTkey.
Figure3‑33:Playingthescenewiththe3rdPersonController
Creatingasimplestaircase
Aswehavelearnthowtocreateobjects,thereareafewshortcutsthatwecould
experimentwithtospeed-uptheprocessofcreatingascene.Todoso,wewillgothrough
asimpleexampleofcreatingastaircasefromboxes:
SelecttheobjectlabeledgreenCube.
Changeitsscalesettingsto(1.5,0.2,1).
Duplicateitseveraltimes.
Movetheduplicatesalongthex-andy-axessothattheyformastaircase.
Playthescenetoexperimentwithyourstaircase.
Managingandsearchingforassetsandobjects
Aswehaveseeninthefirstsectionsofthebook,itispossibletolookforparticularassets
andobjectsinyourprojectandsceneusingsearchwindowsandkeywords.Let’susethese
forourprojectandstartwiththeHierarchywindow:
IfyoulookattheHierarchywindow,youmaynoticeasearchwindowlocatedinitstoprightcorner.Itcanbeusedtolookforitemsinyourscenebasedontheirnames.
Ifwetypethewordcubeinthissearchfield,itwilllistalltheobjectswithanamethat
includesthewordcube.Youmayalsonoticethatinthiscase,asillustratedonthenext
figure,otherobjectsdonotappearinthesceneanymore.
Figure3‑34:Searchinginthehierarchy(cubes)
Inasimilarway,ifwetypethewordgreenforexample,itwilllistalltheobjectswhich
namesincludethewordgreen.Youmayalsonotice,asillustratedonthenextfigure,that
otherobjectsinthescenedonotappearanymoreintheSceneview(theyaregreyed-out).
Figure3‑35:Searchinginthehierarchy(greenobjects)
Let’sseehowwecanperformsearchesintheProjectwindow:
IfweclickontheProjectwindow,youmaynoticeasearchwindowlocatedinitstoprightcorner.
Aftertypingthewordcolor,Unitywillshowallassetswithanamethatincludesthis
word;inourcase,itincludesboththematerialsredColorandgreenColor.
Figure3‑36:Searchingforassets(color)
Usingthewordtileforthesearch,Unitywillshowallassetswithanamethatincludes
thisword;inourcase,itincludesboththetextureandthemateriallabeledtile.
Figure3‑37:Searchingforassets(tile)
Aftertypingthekeywordst:material,Unitywillshowallassetsoftypematerialinthe
project;theseincludethethreeMaterialassetstile,greenColorandredColorthatwehave
createdpreviously.
Finally,aftertypingthekeywordst:texture,UnitywillshowallassetsoftypeTexturein
theproject;theseincludethetexturelabeledtilethatwehaveimportedinourproject.
Anotherinterestingfeatureistheabilitytogroupobjects.Asitis,forexample,wehave
builtastaircase;howeverwewouldliketomoveallthestairsasawhole,ratherthaneach
oftheseindividually.Itispossibletogroupallofthesebycreatingafolder,which,inthe
Hierarchyview,isoftenusedorreferredasanemptyobject.Let’sseehow:
Select:GameObject|CreateEmpty.
Renamethisobjectcontainer-parent.
Next,selectallthecubesthatmake-upthestairs(clickoneachobjectwhilepressingthe
CTRLkeyortheSHIFTkey).
Oncetheyareallselected(exceptfromthecontainer-parentobject),dragallofthemon
theobjectcontainer-parent.
Asyoudo,youwillseeablacktriangletotheleftoftheobjectcontainer-parentinthe
Hierarchyviewandallpreviousobjectslistedunderthisobject.
Ifweselecttheobjectcontainer-parentintheHierarchyviewandusetheMovetool,we
canseethatbymovingthisobject,allthechildrenarealsomovedaccordingly.
Figure3‑38:Groupingobjects
Savingthescene
Atthisstage,wecansavetheproject(File|SaveProject)andalsosaveourscene:
SelectFile|SaveSceneAs…
Chooseanameforyourscene,forexamplescene2.
PressSave.
Bydefault,thescenesaresavedinthecurrentproject.Youcanseeallscenesincludedin
yourprojectbylookingattheAssetsfolderorbyusingthesearchfieldintheProject
windowwiththekeywordst:scene(todisplayallthescenepartofthecurrentproject).
WheneveryouaresavingafileinUnityorimportingassets,thesefileswillbesavedin
theactivefolder(thefolderthatiscurrentlyselected).So,tosaveafileinaparticular
folder,youwillneedtocheckthatthisfolderhasbeenselectedintheProjectwindow
beforehand.
Exportingourscenetoawebbrowser
Whilewehavecreatedaverybasicscene,itwouldbegreattoexportitandseehowitwill
lookinabrowser.
Select:File|BuildSettings:thiswindowhelpstospecifythesettingsforthegamewe
wouldliketoexport,includingthescene(s)tobeusedandtheformatoftheoutput.
Fornow,wewillonlyincludethecurrentscene.
InthesectionSceneInBuild,selectanddeleteanyitempresentinthelist.Thisissothat
notallscenesintheprojectareincludedinthebuild.Inotherwords,wearebeing
selectiveastowhatsceneshouldbeincludedtopossiblyreducethesizeofthefiles
createdforthebuild.
Oncethelistisclear,clickthebuttonAddCurrentScenetoaddthecurrentscenetothe
build,andselectWebPlayerinthePlatformsection.
Figure3‑39:Buildsettings
LeavealltheotheroptionsasdefaultandclickonthebuttonlabeledBuildandRun.
Anewwindowwillappearaskingforthenameofthebuild.YoucantypemyFirstGame.
ThiswillcreateafolderandaUnityfilewiththesamenamewithinyourprojectfolderby
default.Thisbeingsaid,youcanchoosetoexportthegametootherlocationsofyour
choice.
Oncethebuildiscomplete,yourdefaultbrowserwillbelaunchedandthegameshould
appear.
Figure3‑40:Viewingyourgameinabrowser
Pleasenotethatatthismomentintime,andalthoughWebexportworksinUnity,itmay
nobesupportedbyChrome,asthesupportfortheNPAPIplugin,whichisusedwhen
displayingaUnitysceneinabrowser,isbeingprogressivelydroppedbyseveral
browsers(forsecurityreasons).
IfyouareusingChrome,thefollowingsolutionistemporarilyavailableuntilChrome45
(late2015):
Intheaddressbaratthetopofthescreen,typechrome://flags/#enable-npapi
Inthenextwindow,clickthelinkthatsaysEnableundertheEnableNPAPIflag.
Inthebottom-leftcornerofthepage,clicktheRelaunchNowbutton.
Levelroundup
Summary
Inthischapter,wehavelearnedaboutseveralcorefeaturesinUnity.Webecamemore
confortablewiththeinterfaceandlearnedhowandwhytousethedifferentviews.Wealso
learnedhowtoaddandtransformbuilt-inassets,includingcubes,lights,andcameras.We
alsolookedintohowtomodifytheappearancesofeachboxbyimportingorcreating
materials.Buildingonthisknowledge,wecreatedasimplelevelwithastaircaseand
ground,andaddedtwotypesofcontrollerssothatwecouldnavigatethroughthescene.
Welookedatdifferentwaystomanagetheassetsincludedinourprojectbygrouping
them(usingemptyobjects)andsearchingthemwithcorrespondingsearchwindowsand
keywords.Finally,wehavelearnedhowtoexportourscenesothatitcanbeviewedina
webbrowser.
Quiz
Itisnowtimetotestyourknowledge.Pleaseanswerthefollowingquestions(e.g.,Yesor
No).Theanswersareavailableonthecompanionwebsite
(http://www.learntocreategames.com/learn-unity-ebook).
1.InUnity,allfilesandscenesarealwayssavedinthefolderAssets.
2.Whenimportingapackage,anyofitsitemscanbeimportedselectively.
3.ForeachtextureusedinUnity,acorrespondingmaterialiscreatedautomatically.
4.TheRGBcodeisusedforcolors.
5.ThekeyQistheshortcutfortheMovetool.
6.ThekeyRistheshortcutfortheScaletool.
7.TheRecttoolcanbeusedtoselectallobjectsinaparticulararea.
8.InUnity5,theThird-PersonControllerincludesabuilt-incamerathatfollowsits
movementbydefault.
9.Thesyntax“t:material”intheProject’ssearchwindowwillreturnobjectsforwhichthe
labelincludesthelettertorthewordmaterial.
10.ItispossibletoseethecontentofboththeGameviewandtheSceneviewatthesame
time.
Checklist
Youcanmovetothenextchapterifyoucandothe
following:
Addacombinationofbuilt-inobjectstoyourscene.
Addacolororatexturetoyourobjectsinthescene.
Includebuilt-inpackages(assets)thatyoucanuseto
walkacrossthescene(i.e.,first-orthird-person
controllers)oraddcameraeffects(e.g.,tofollowa
target).
Manageandsearchforassetsinyourprojectsusing
relevantsearchwindowsandkeywords.
Groupobjects(usingemptyobjects),andcreatea
parentobject,sothattransformationsareappliedtoallof
thechildren(ratherthanindividualtransformations).
Changethelayoutofyourproject’swindowstosuit
yourworkflow.
Challenge1
Nowthatyouhavemanagedtocompletethischapterandthatyouhavegathered
interestingskills,let’sputthesetothetest.Thisparticularchallengewillgetyouto
becomesupercomfortablewithshortcuts.
Createarobotthatdoesnothavetobeanimated,asfollows:
Usebuilt-inshapes(e.g.,spheres,boxes,orcylinders).
Combinetheseshapestocreatethedifferentpartsoftherobot.
Grouptheseshapesforthearmsandlegs,forexample.
Useduplicationtospeed-upyourworkflow(e.g.,duplicatetheleftlegortheleftarm).
Challenge2
Createaplatformgamewheretheplayerneedstojumpbetweenboxes(platforms)to
reachtheendofthelevel;youcandoasfollows:
Createanewscene.
Add,move,andresizeboxes.
Addtexturestotheseboxes.
Addafirst-orthird-personcontroller.
Testthegame.
ImportthescriptcalledresetPlayerfromtheresourcefolderdownloadedfromthe
companionwebsiteanddraganddropthisscriptontopoftheFirst-orThird-Person
Controller.Thisscriptwillensurethatyourcharactercontrollerisresettoitsinitial
positionifitmissesaboxandfalls.Youdon’tneedanyscriptingskillsforthis,but,ifyou
arecurious,youcanlookathowthescriptisdesigned.
Testthegameandcheckthatwhenevertheplayerfalls,itisresettoitsinitialposition.
4
TransformingBuilt-inObjectstoCreate
anIndoorScene
Thischapterhelpsyoutocreateanindoorsceneusingbasicshapesandtextures.
Followingthepreviouschapter,youwilluseyourskillstomodifyshapes(e.g.,move,
scale,rotate).Youwillalsolearntoconfigurelights,andtextures(e.g.,tiling).
Aftercompletingthissection,youshouldbeableto:
Bemoreconfortablewithmanipulatingandtransformingobjects.
Understandhowatexturecanbetiledoveranobject.
Configuretheintensityofalight.
Understandhowtoset-upambientlight.
UnderstandhowtousetheRecttooltospeed-upthedesignprocess.
Theplan
Whenyoustartcreatingagame,andalthoughtherearemanyresourcesavailableout
there,youmayjustwanttocreateaquickmockuptotestthekeyfeaturesbeforeyoucan
(orhiresomeonewhocan)createamorepolishedlevel.Althoughyoumayhavea3D
modelingbackground,manybeginners,whomaynothavethisskill,mayneedtobeable
tocreatetheirlevelfastwithbasicshapes.Thischapterwillhelpyoutodojustthat:to
createafunctionallevelwithrelativelysimpleshapes.Forourfirstlevel,wewillcreatea
scenewiththefollowingfeatures:
Amaze(i.e.,indoorscene)withlights,texturedwalls,agroundandaceiling.
Safeareas.
Dangerousareaswheretheplayercouldbeexposedortrapped.
Tocreatethisenvironment,wewillbegoingthroughthefollowingprocess:
Useapredefinedmapofthemazeintheformofanimage.
Usethismaptoaddobjectstoourscene.
Removethismap.
Addtexturestoallobjectsinthescene.
Withoutapredefinedmap,itmaybedifficulttoknowwheretoaddthedifferentobjects
thatwillmakeupyourscene.Youcan,ofcourse,usecoordinates(placetheobjectbased
onalistofpredefinedcoordinates);however,usingamap,youcanvisuallyassess
whethereachobjecttobeincludedisattherightlocation,asyouexpected.Inourcase,we
willbetexturingthefloorwiththemap,thenaddobjectsatopthefloor,basedonthe
outlineofthemaze,andthenreplacethistexture(i.e.,theoutline)withtiles,onceallthe
objectshavebeenadded.
Thelayoutofourlevelisillustratedonthenextfigure;itessentiallyconsistsofa
successionofcorridors.
Figure4‑1:Outlineofthemaze
Asyoucansee,thisisarathersimpleblackandwhiteimagethatwascreatedin
Photoshop.Itconsistsofawhitebackground(whichsymbolizesemptyspaces)andblack
rectanglesofdifferentsizes.Youcancreateamapofyourchoiceveryeasilyusing
PaintorGimpalso.TheideaofthismapistosimplifythecreationofthemazeinUnity
byspecifying,evenroughly,thelocationofthedifferentpartsofthemaze,sothatwe
don’thavetoguesswheretoaddobjects,butinsteadfollowaguideandourinitialplan.
Forthepurposeofthischapter,thisimagewascreatedusingPhotoshop.Itssizeis100by
100pixels,and,ifyouareusingPhotoshop,youcanalsoactivatethegridlinesevery5
pixels(subdivisionseverysecondpixel).
Creatingasceneandimportingnecessaryassets
Beforewestarttocreatethisenvironment,wewillcreateanewsceneandacorresponding
folderwherealltheassetsthatweneedwillbestored.Wewillalsoimportsomeofthe
texturesrequiredforthislevel.
First,let’screateanewscene:
Assumingthattheprojectwehavecreatedinthepreviouschapterisopen(otherwise,
youcanopenitusingFile|OpenProject),createanewscene(File|NewScene)andsave
itaschapter4(oranyothernameofyourchoice).Oncethisisdone,wehaveablank
scenewithnoobjectsintheHierarchyorSceneview,exceptfromacameraandthelight.
Wecannowcreateafolderforourscene.Whilethisisnotcompulsory,ithelpsto
organizeourprojectandtoincludeandsaveallrelevantassetsusedforthissceneina
particularfolder.
IntheProjectwindow,clickonthefolderlabeledAssets,andthenselectCreate|Folder
fromthemenulocatedinthetop-leftcorner.ThiswillcreateanewfolderlabeledNew
FolderwithinthefolderAssets.Notethatwecouldalsohaveright-clickedonthefolder
AssetsandselectedtheoptionCreatefromthecontextualmenutoperformthesame
action.
Let’srenamethisfolderchapter4(oranyothernamethatyouwouldliketouseinstead):
right-clickonthefolder,selecttheoptionRenamefromthecontextualmenu,andenterthe
newnameforthisfolder(e.g.,chapter4).
Atthisstage,youhavealreadydownloadedtheresourcesforthisbookfromthe
companionwebsite.Forthischapterwewillneedtoimporttheimagesbricks.jpg,
ceiling.jpg,andgameMap.jpg.Wecanimportthesetexturesinatleasttwoways.
Usingdrag-and-drop:
OpenthefolderAssets|chapter4inUnity.
Locatethefolder,thatyouhavedownloadedandunzippedfromthecompanionwebsite,
inyourfilesystem.
Drag-and-droptheimagesbricks.jpg,ceiling.jpg,andgameMap.jpgtothefolder
chapter4inUnity.
UsingtheImportoption:
Selectthefolderchapter4inUnity.
SelectAssets|ImportNewAssetfromthetopmenu.
AnewwindowcalledImportNewAssetwillappear.
Locatethefolderwhereyouhavesavedtheimagesonyoursystem.
SelectthefiletoimportandclickImport.
Repeatthepreviousstepforeachoftheimagestobeimported.
Definingtheoutlineofthemaze
Atthisstage,wearereadytostartcreatingourmaze.First,wewillcreateacubethatwill
beusedfortheground:
Createanewcube(selectGameObject|3DObject|Cube).
UsingtheInspector,ensurethatthepositionofthiscubeis(0,0,0).
RenamethiscubegroundusingtheHierarchywindow(CTRL+Enter)ortheInspector.
UsingtheInspector,changethescalepropertiesofthisobjectto(100,1,100)sothatit
isscaled-uponthex-andz-axes.
Wewillnowapplyatexturetothisobject:
Tomakeiteasiertoseethechanges,wecanchangetheviewtolookattheobjectfrom
they-axis.Thiscanbedone,aspreviously,usingtheGizmolocatedinthetop-right
corner,byclickingonitsy-axis.
Oncethisisdone,wecannavigatetothefolderthatincludesthetexturethatwehave
justimported,includingtheimagefortheground,usingtheProjectwindow(i.e.,Assets|
chapter4).Onceyouhavelocatedthisfolder,aswellasthetexturethatweneedtousefor
theoutline(gameMap.jpg),draganddropthistexturefromtheProjectwindowtothe
objectlabeledgroundintheScene(ortheHierarchy);thiswill,aswehaveseeninthe
previoussection,applythetexturetothegroundobject,asdescribedonthenextfigure.
Figure4‑2:Applyinganewtexturetotheground
Asforpreviously,youwillnoticethatafoldercalledMaterialswascreatedwithinthe
folderchapter4,andthatitcontainsanewmateriallabeledgameMap.Ifyouremember,
thisfilewilldefinehowourtexturewillbeexpressedandrendered.
Ifweclickonthismaterial(i.e.,thematerialgameMapthatislocatedinthefolder
Material),andlookattheInspectortocheckitsproperties,youwillseethatitstiling
propertiesare(1,1),whichmeansthatthetextureistiledonlyonceonboththex-andthe
y-axis,andthat’sexactlywhatweneedbecausethetextureissupposedtorepresentthe
entirelevel.Thisisthereasonwhywewillleavethisdefaultoptionasitis.
Addingwallsusingsimpletransformations
Nowthatthegroundhasbeendefined,itistimetocreatewallsandotherrooms,basedon
cubes;let’screateourfirstroom:
Createanewcubeandrenameitroom1.
Positionthiscubejustabovetheground(e.g.,Position:y=1).
Youmayalsochangetheview(ifyouhavenotalreadydoneso)toatopviewusingthe
gizmo,sothatyoucanviewthescenefromthey-axis.
Wewillnowperformaseriesoftransformationsonthiscubesothatitfitsoneoftheblack
rectanglesonthegroundtexture:
Selectthecuberoom1.
SelecttheRecttoolusingtheshortcutRorbyselectingthistoolinthecorresponding
toolbarasillustratedonthenextfigure.
Figure4‑3:SelectingtheRecttool
Whenthistoolhasbeenselected,zoom-inontheobjectroom1(e.g.,double-clickonthis
objectintheHierarchy),youshouldseebluehandlesappearingateachcornerofthecube,
asdescribedonthenextfigure.
Figure4‑4:UsingtheRecttoolonacube
Wecannowresizethecubebydragginganddroppingoneofitshandlessothatitmatches
thedesignatedblackrectangleontheoutline(i.e.,themapdefinedbythetextureonthe
ground).
Figure4‑5:Matchingthegroundtexture
Figure4‑6:Completingthefirstroom
Aftersuccessiveiterations,wehavemanagedtocreatethefirstroombymatchingthe
textureontheground,asillustratedonthenextfigure.
Figure4‑7:Completingthefirstroom(continued)
Atthisstage,wehavemanagedtorescaletheroomalongthex-andz-axes;however,we
alsoneedtomodifyitsheight.Wewouldliketheceilingtobe2.5metershigh;however,
itscurrentyposition,whichisusuallycalculatedfromitscentre,is0;thismeansthat,
effectively,ifwesetayscalefactorof2.5,theactualdistancebetweenthegroundandits
centerwillbe1.25meters.Thismeansthatonlyhalfofthecubewillbeabovetheground;
soweneedtomovethiscubeupwards.Let’sapplythesechangesintheInspector
window:
Checkthattheobjectroom1isselected.
IntheInspectorwindow,modifytheypositionattributeto2.5.
IntheInspectorwindow,modifytheyscaleattributeto5.0.
Oncethisisdone,wecanapplyatexturetothisroom:
NavigatetothefolderAssets|chapter4(oranyfolderwhereyouhavestoredthe
picturesforthischapter).
Draganddropthetexturebrickslocatedinthisfoldertotheobjectroom1;thiswillalso
createacorrespondingmaterialinthefolderlabeledMaterials(Assets|chapter4|
Materials).
Changethetilingofthistexturebymodifyingthetillingpropertiesofthebrickmaterial
(locatedintheMaterialsfolder)to(x=10,y=2).Thissettingisarbitraryandyoumayuse
differentscalingpropertiesbasedonthetexturethatyouhaveapplied.Tomakesurethat
thetilinglooksrealistic,youmayfirstzoom-inontheobject,andthenmodifythetiling
properties,sothatyoucanobserveandapplythexoryscalingvaluesthatworkbestfor
you.
Figure4‑8:Addingatexturetotheroom
Onceyouarehappywiththelookoftheroom,wecanduplicatethisroomandresizeitto
createanotherroom:
Duplicatetheobjectroom1intheHierarchyviewandcallthenewobjectroom2.
Movetheduplicatenearanotherblackrectangleontheoutline,andresizeitsothatit
matchestheareaperfectly(i.e.,atthisstage,onlythexandzpositionandscaleattributes
needtobemodified).YoucanusetheMovetooltomovetheobject,andtheRecttoolto
resizeit.
Figure4‑9:Duplicatingtheinitialroom
Youcanrepeatthisprocesstocompletetheentiremaze.
Creatingtheexternalwalls
Onceyouhavecreatedallthedifferentrooms,themazeshouldlookasdescribedinthe
followingfigure.
Figure4‑10:Themazealmostcompleted(withoutexternalwalls)
Youmaynoticethatthetexturethatweusedfortheroomsdiffersdependingontheroom
itwasappliedto.Thisisbecausethetilingwasbasedonthelengthoftheinitialroom;we
canleavethisoptionasitisfornow;however,ifyouwantedtoincreasetheaestheticsof
someoftherooms,youcoulddefinespecificmaterialsforsomeofthemsothatthetiling
issetaccordingly(sincethetilingislinkedtothematerial,achangeinthetilingsettings
involveschangingorcreatinganewmaterial).
Soatthisstage,ourmazeisalmostcomplete,itonlyneedsatleastthreeelements:
externalwalls,aroof,andsomelight.
Solet’screatetheexternalwalls.
Tocreatetheexternalwalls,wecanstartbycreatingaduplicateofanyotherwall,and
thenresizingthisduplicate.Forexample,wecould,asillustratedinthenextscreenshots:
Duplicatetheboxlocatedinthebottom-leftcornerofthescreen(CTRL+D).
Renamethisduplicate.
Resizetheduplicatetoobtainoneoftheexternalwalls(usingboththeRectandMove
tools).
Checkthatthewallmatchestheboundarydefinedbytheoutlineimage.
Figure4‑11:Duplicatinganexistingobject
Figure4‑12:Creatingthefirstexternalwall-part1
Figure4‑13:Creatingthefirstexternalwall-part2
Figure4‑14:Creatingthefirstexternalwall-part3
Asyoucansee,theprocessisrathereasy,andwecanrepeatittocreatethethreeother
externalwalls:
Duplicatetheexternalwallthreetimes.
Transformandmovetheduplicatestotheircorrespondinglocationontheoutline.
Addingafirst-personcontrollertonavigatethroughthe
scene
Atthisstage,wehavemanagedtocreatethefloor,severalrooms,andexternalwallsfor
ourmaze,anditwouldbegreattobeabletonavigatethroughthemaze.Ifyouremember
thefirstchaptersofthebook,weusedCharacterControllerstonavigatethroughour
platformgame.Wewilldotheexactsamehere,andaddaCharacterControllertothe
scenesothatwecanwalkthroughthemazeandseehowitwillappeartotheplayer.
Becausethescenethatyouarenowcreatingispartofthesameprojectastheoneusing
platforms,thecharactercontrollersprefabsarestillavailableintheStandardAssets
section.Inotherwords,wewillnotneedtoreimportthispackage.Solet’sdothe
following:
IntheProjectwindow,navigatetothefolderStandardAssets|Characters|
FirstPersonCharacter|Prefabs.
Figure4‑15:Addingafirst-personcontroller
Draganddroptheprefab(bluebox)withthelabelFPSControllertothescene.
Figure4‑16:Addingafirst-personcontroller(continued)
OncetheFPSControllerhasbeenadded,anewobjectlabeledFPSControllershould
appearintheHierarchywindow.
Double-clickonthisitemintheHierarchywindowtozoom-inonthisobject.
IntheSceneview,movetheFPSControllersothatitisslightlyabovetheground;asyou
willseeonthenextscreenshot,mypositionfortheFPSControlleris(-2.3,1.37,-9.25);
however,thesemayvarydependingonhowyouhaveimplementedthemaze.
Figure4‑17:Adjustingthefirst-personcontroller
Atthisstage,ifyouclickontheGametab,youmayseeaglimpseofthemazeviewed
throughthelensesoftheFPSController,asillustratedonthenextfigure.
Figure4‑18:SeeingtheviewfromtheFPSController
Changingthetextureoftheground(removingtheimage
template)
Atthisstage,ourlevelisprettymuchreadytobeviewed,exceptfortheground.Ifyou
remember,thetextureusedforthegroundhasbeen,untilnow,atemplatewithwhiteand
blackboxesthatindicatedwheretoaddcubesthatdefinedrooms.Becausewehave
completedthelayoutforthemaze,wedon’tneedthistextureanymore.Wecan,instead,
useamorerealistictexturefortheground,suchasthetiletexturethatwehadinitially
appliedtothegroundinthepreviouschapter.Solet’smakethischange:
IntheSceneview(ortheHierarchyview),clickonceontheobjectlabeledgroundso
thatwecanseeitspropertiesintheInspectorwindow.
Oncethegroundhasbeenselected,lookattheInspectorwindowandlocatethe
componentcalledMeshRenderer.
Withinthiscomponent,inthesectioncalledMaterial,click(onthesmallcircle)tothe
rightofthetexturegameMapsothatwecaneditandchangethetextureallocatedtothis
object.
Figure4‑19:Changingthetexturefortheground
Afterclickingonthisicon,anewwindowlabeledSelectMaterialwillappear,sothatyou
canselectanothermaterialfortheground.
Atthetopofthiswindow,enterthetexttileinthesearchfield.Thisshouldfilterthe
texturesintheprojecttoonlydisplaythoseforwhichthenameincludesthewordtile.You
canthenselectthetiletexturefromtheresultsofthesearch.
Figure4‑20:Selectinganewtexture
Onceyouhaveclickedonthistexture,theInspectorwindowshouldnowlistthis
materialfortheobjectgroundashighlightedonthenextfigure.
Figure4‑21:Texturesetfortheground
YouwillalsoseethatthetextureofthegroundhaschangedintheGameandScene
views.
Afterthischange,itisnowtimetoplayoursceneandnavigatearoundit:
PressthePlaybutton(orCTRL+P).
Navigatethroughthescene.
Itshouldlookasdescribedonthenextfigure.
Figure4‑22:Scenewithagroundtexture
Addingaceilingtothemaze
Onceyouhavecheckedthattheenvironmentlooksasexpected,wecanstopplayingthe
scene.Atthisstage,thelevelisfunctional;however,asmentionedearlier,itwouldbe
greattoincludearoof.Thiscanbedoneeasilybycopyingtheground,movingitup,and
changingtheassociatedtexture.Wewillusethesametechniquesasbefore(byusingthe
MovetoolandchangingtexturesintheInspector):
UsingtheHierarchywindow,searchfortheobjectground.
Onceyouhavelocatedthisobject,duplicateit(CTR+Dorright-click+duplicate).
Renametheduplicateceiling.
Inthesceneview,andusingtheMovetool,moveuptheobjectlabeledceilingsothatit
isslightlyabovetheotherwalls,forexampletotheposition(0,5,0).
Figure4‑23:Positionattributesfortheground
Oncethisisdone,wejustneedtoapplyatexturetothisceiling:
Importthetexturecalledceilingfromthefolderdownloadedfromthecompanion
websiteandsaveitinafolderofyourchoicewithinUnity(e.g.,Assets|chapter4).
InUnity,intheProjectwindow,gotothefolderwhereyouhavesavedthistexture.
ThendraganddropthistextureontotheceilingobjectintheHierarchyorSceneview.
Figure4‑24:Applyingatexturetotheceiling(beforechangingthetilingattributes)
Asyoudraganddropitontheceiling,youwillnoticethatthetextureistiledonlyonceon
thesurfaceofthisobject;so,aspreviously,wewillneedtochangethetilingpropertiesof
thematerialassociatedtothetexturewehavejustused.
Remember,wheneveranewtextureisappliedtoanobject,anewmaterialiscreatedin
thefoldercalledMaterials.Thismaterialwilldictatehowthetextureistobedisplayed
(e.g.,includinghowmanytimesitistobetiled).
Youmayalsonotice,intheProjectwindow,thatanewfoldercalledMaterials,hasbeen
created(orupdated,ifthetexturehasbeensavedinthesamelocationastheprevious
textures)inthefolderwherethistexturewassaved.
Openthisfolder(i.e.,Assets|chapter4|Materials).
Figure4‑25:Selectingthematerialforthetextureceiling
Withinthisfolder,select(i.e.,clickon)thematerialcalledceiling.
Oncetheobjectisselected,lookattheInspectorwindow,andchangethetiling
propertiesofthisobjectto(x=20;y=20).
Figure4‑26:Changingthetilingpropertiesofthecurrentmaterial
WhenlookingbackattheSceneview,youcannowseethatthetilingofthetextureforthe
ceilinghaschanged,asillustratedonthenextscreenshot.
Figure4‑27:Ceilingwithanewtiling(20by20)
Wecannowplayourscenetoseehowthisnewtexturelookslike.
Figure4‑28:Ceilingwithanewtiling
Asyounavigatethroughthemaze,wemaywelldiscoverareasthatarebright,wherethe
lightfromoutsidethemazeshinesthrough,indicatingthattheceilingisprobablynot
coveringthemazeproperly.Butyoucanalwaysreadjustitssizeandpositionatalater
stagetoensurethatthisisfixed.
Figure4‑29:Brightareasinthemaze(lightfromoutside)
Youmaybewonderingwhyyoucanstillseethewallsiftheenvironmentisperfectly
closed.Wewillseethisinmoredetaillateron,butinanutshell:yourscenehasdefault
attributes,andsomeofthesearerelatedtotheamountofambientlightinthescene.By
default,evenifnolightshavebeenaddedtothescene,therewillbesomeambientlight.
This,ofcourse,canbemodified,andwewilldosointhenextsection.
Addinglighttothescene
Onceyouhaveamendedthemaze,wewillstartaddinglighttoit,tocreatesomedarkand
brightareas.Inyourgame,thiscouldbeusedtoconcealareasortohighlightroomsor
corridorswheretheplayershouldgo.TherearemanydifferenttypesoflightsinUnity,
andforthetimebeing,wewilljustusePointLightstosimulatethelightcreatedfroma
bulb,oratorchlight,thatshinesfromaspecificpointinalldirections.
Becausetheceilingisnowthetop-mostobjectwhenlookingatthescenefromthey-axis,
wecantemporarilydeactivateitsothatitiseasiertoaddandmoveobjectswithinthe
maze.Todoso:
SelecttheobjectlabeledceilingintheScene(ortheHierarchy)view.
IntheInspectorwindow,deactivatethisobject(byuncheckingtheboxlocatedinthe
top-leftcorneroftheInspectorwindow).
Oncethisisdone,wecanstarttoaddlightstothescene:
FromtheGameObjectmenu,selectLight|PointLight.
Figure4‑30:AddingaPointLighttothescene
ThiswillcreateaPointLight.
Iftheobjectthatyouhadselectedpriortocreatingthelightswas,forexample,the
FPSController,thelightwillbecreatedatthesamelocation.Inotherwords,new
objectsarecreatedatthesamepositionastheobjectselectedbeforethenewobjectis
created.
YoushouldnowseeanewobjectlabeledPointLightintheHierarchyaswellasanew
lightintheSceneview.
Figure4‑31:Addingapointlight
SelectthisnewobjectintheHierarchyview,andlookattheInspectorwindowtoseethe
propertiesofthislight.
IfyoulookatthecomponentcalledLight,youwillseeseveralpropertiesthatwillmake
itpossibletocustomizethelight,includingRange,Color,orIntensity.
Fornow,wewillchangetheRangeto20(i.e.,20meters)andtheIntensityto1.63.
Figure4‑32:Modifyingthelightproperties
Oncethesechangeshavebeenmade,let’sdeactivatetheexternallight:
LocatetheobjectlabeledDirectionalLightinthescene.
IntheInspectorwindow,deactivatethisobject(byuncheckingtheboxlocatedinthe
top-leftcorneroftheInspectorwindow).
Youshouldnowseethatthesceneismuchdarker,asillustratedonthenextscreenshot.
Figure4‑33:Scenewithouttheexternallight
Youcanalsoreactivatetheceiling(i.e.,selecttheceilingandchecktheboxlocatedin
thetop-leftcorneroftheInspectorwindow)andplaythescenethatshouldnowlooklike
thefollowingfigure.
Figure4‑34:Navigatingthescenewithoutexternallight
Aftercheckingthescene,wecanreproducethelaststepstoincludemorelights,byeither
duplicatingandmovingthePointLightwehavecreatedorbyusingthemenu
GameObject|Light|PointLight,asfollows:
Temporarilydeactivatetheceiling:thiswillmakeiteasiertomovethelights.
DuplicatethePointLightthatyouhavecreatedpreviouslyseveraltimestolocationsof
yourchoice,makingsurethatmostcorridorsarelitupproperly.
ModifythesettingsforeachlightandamendtheirRange,IntensityorColortocreate
specialeffectsofyourchoice.
Reactivatetheceiling,playthesceneandseehowtheselooklike.
Figure4‑35:Includingadditionalpointlights
Asyoucanseeonthenextpicture,thepointlightscanbeusedtohighlightpointsof
interest.
Figure4‑36:Navigatingthenewscene(withmorepointlights)
Lastbutnotleast,weneedtomakesurethatareaswithnolightarecompletelydark,
regardlessoftheambientlight;solet’smodifytheprojectsettingsaccordingly.
Openthemenu:Window|Lighting.Thiswindowwilldealwithmostofthelight
settingsforourproject.
Figure4‑37:Accessingthelightingproperties
TheLightingwindowshouldthenopen.Asyouwillsee,itincludesseveraltabsand
sections.Fornow,clickonthetabcalledScene.
Figure4‑38:Modifyingthelightingproperties(ambientlight)
InthesectioncalledEnvironmentLighting,reducetheoptionAmbientIntensityto0;as
youdo,lookatthesceneviewandobservehowthemazeprogressivelybecomesdarker
anddarker.
Oncethisisdone,youcanclosetheLightingwindowandplaythesceneagain.
Levelroundup
Summary
Inthischapter,wehavebecomemorecomfortablewiththecreationofanindoor
environmentandwelearnedhowtocreateamazefrombuilt-inobjectssuchasboxes,
pointlights,orcameras.Weusedtheskillsacquiredintheprevioussectiontotransform
objectsandcreateafullyfunctionallevel.
Quiz
Itisnowtimetotestyourknowledge.Pleaseanswerthefollowingquestions(e.g.,Yesor
No).Theanswersareavailableonthecompanionwebsite
(http://www.learntocreategames.com/learn-unity-ebook).
1.TheshortcuttomoveanobjectisQ.
2.TheshortcuttorotateanobjectisR.
3.TheAmbientLightingcanbemodifiedusingthemenuWindows|Lights.
4.IntensityisanattributeofbothAmbientandPointlights.
5.Ifnolightshavebeenaddedtothescene,thescenewillbecompletelydark.
6.Newobjectsarealwayscreatedattheposition(0,0,0).
7.Tilingisoneoftheattributesofalltexturesusedinascene.
8.Onceatexturehasbeenappliedtoanobjectitcannotbereplacelater.
9.Atilingpropertyof(1,1)meansthatthepicturewillberepeatedonceonboththex-and
they-axis.
10.TheshortcutCTRL+Disusedtodeleteanobject.
Checklist
Youcanmovetothenextchapterifyoucandothe
following:
Applyatemplatetocreateascene.
Duplicateobjects.
Moveandtransformobjectstocreateamaze.
Changethetilingpropertyofatexture.
Addlightstoascene.
Modifytheintensityandcolorofthedefaultambient
lightforascene.
Challenge1
Forthisparticularchallenge,youwillneedtocreateanewmaze,basedonanewtemplate
asfollows:
ImportthetexturegameMap2fromthefolderthatyouhavedownloadedfromthe
companionsite.
Applythesametechniquesasbeforetorecreatethemazebasedonthisoutline.
Addlightsatlocationsofyourchoice.
Challenge2
Forthischallenge,youwillneedtocreateyourownoutlineusingtheimagemanipulation
toolofyourchoiceandthenapplyittocreateatotallynewmazeofyourowndesign!
Youcouldproceedasfollows:
Createanewimagewithasizeof100pixelsby100pixels.
Setthebackgroundtowhite.
Settheforegroundcolourtoblack.
Createthemazeusingabrushofsize1.
Saveyourimageinthepngorjpgformat.
ImportthisimageintoUnity.
Createanewscene.
Usethisnewtemplatetocreateyourownnewmaze.
5
CreatinganOutdoorScenewithUnity’s
Built-inTerrainGenerator
Inthischapter,wewillstarttouseUnity’sbuilt-inassetpackagestocreateanoutdoor
sceneandnavigatethroughitusingdifferenttypesofvehicles.
Aftercompletingthissection,youshouldbeableto:
Createarealisticlandscapefromatemplate.
Createaterrainandmodifyittoproducehillsandvalleys.
Simulatewater.
Addandcontrolbuilt-invehiclessuchascarsandaircrafts.
Addandcustomizecamerastoobtaintop-downviewsoftheenvironment.
Theplan
Forthischapter,wewillcreateanislandandwewillalsoaddtwovehiclestoit(acarand
aplane),sothatyoucannavigatethroughandabovetheislandeasily.Sotheplanispretty
simple:
Importatemplatethatwewillusetodrawtheoutlineoftheenvironment.
Createaterrainbasedonthistemplate.
PaintoverthetemplateusingUnity’sbuilt-inTerraintools.
Createhillsandvalleys.
Addtreesandothertypesoffoliage.
Addbuildingsbasedonboxes.
Addanddriveacarinthisenvironment.
Addandpilotanairplane.
Customizethecamerassothatthevehiclesarealwaysinsight.
Thenextscreenshotisapreviewofwhatyouwillhaveaccomplishedaftercompletingthis
chapter.
Figure5‑1:Previewofthecaronthebeach
Figure5‑2:Previewoftheislandwithtrees
Figure5‑3:Previewoftheislandwithabuildingandhillsinthebackground
Asyoucansee,youwillbeabletocreateaverysimple,yetrealisticenvironment.
Theislandoutline
Forthislevel,wewillbecreatinganisland.Asperthepreviouschapter,wewillbeusing
animagecreatedinPhotoshoptodefineitsoutlineandmainfeatures.
Figure5‑4:Theoutlineoftheisland
Asyoucansee,thisisarathercoarseoutline,butitgivesanideaoftheshapeofthe
island.Youmaynoticethefollowing:
Watersurroundingtheislandinblue.
Sandformostoftheisland.
Brownpatchestohighlightpaths.
Greendotstoidentifythelocationoftrees.
Blackrectanglestoindicatethepositionofbuildings.
Alakeinthemiddle(bluecircle).
Thisimageis500pixelsby500pixelsanditwillbemappedsothat1pixelroughly
equatesto1meterinUnity.Ifyouwanttocreateyourownoutline,youcandosoeasily
usingthesesettings.Themapdoesnothavetobeextremelydetailedbecause,asyouwill
seelater,wewillbeabletopaintoveritandalsoremove(i.e.,erase)someofitselements.
WhatisimportantfornowisthatyouhaveanoutlinethatyoucanusedirectlyinUnity.
Downloadingnecessarymaterial
Allmaterialnecessaryforthischapterisincludedintheresourcepackthatyouhave
downloadedatthestartofthebook;ifyouhavenotdoneso,youcanfindthismaterialon
thecompanionwebsiteonthefollowinglink:
http://www.learntocreategames/learn-unity-ebook/
Importingnecessaryassets
Atthisstage,wearereadytostartwithourisland.Ifyourememberwell,wewillbe
addingtreesandaterrainthatwillmimictheshapeoftheisland;forthispurpose,weneed
toimportspecificpackagestobeabletocompletethesetasks.Thesepackagesinclude
terrainassetsandwaterassets.Theterrainassetsincludeallnecessarytexturesandobjects
neededtobuildandamendaterrain,whilethewaterassetsmakeitpossibletocreate
realisticwatereffects.Let’simporttheseassets:
InUnity,select:Assets|ImportPackage|Environment.
AnewwindowlabeledImportingPackage,shouldappear.Thiswilltakeafewseconds
orminutes,dependingonthespeedofyourcomputer.Asforotherimportingwindows,it
willlistalltheitemsthatyoucanimportwithinthispackage.
Figure5‑5:ImportingtheEnvironmentpackage
Wewillbeimportingallassetsinthispackage,sowecanleavealltheboxestickedand
clickonthebuttonImport.
Oncetheimportiscomplete,youwillnoticeanadditionalfolderlabeledEnvironment
withinthefolderStandardAssets,asillustratedonthenextfigure.
Figure5‑6:LocatingtheEnvironmentpackageintheAssetsfolder
Asyoucansee,thisfolderincludesseveralotherfolderswithassetsrelatedtoterrains,
water,ortrees.
Atthisstagewehaveallthenecessaryassetstocreateourisland,exceptfromtheoutline
map.Solet’simportit:
Switchtoyourfilesystem(e.g.,explorerorFinder).
Locatethefolderwhereyouhavedownloadedtheresourcepackatthestartofthisbook.
SelectthefilelabeledgameMapOutdoors.png.
DraganddropthisfileinsidetheProjectwindowasillustratedinthenextfigure.
Figure5‑7:Importingtheoutlinefile
Creatingtheoutlineoftheisland
Atthisstage,wehavemostoftheassetsthatwerequiretostart.Solet’screatetheterrain:
Createanewterrainbyselecting:GameObject|3DObject|Terrain.Whileweused
boxestocreatefloorsbefore,terrainsbehavelikerealterrainsinthattheycanberaisedor
lowered;theyincludetreesandotherfeaturestocreaterealisticoutdoorscenes.
ThisshouldcreateanewobjectlabeledTerrainintheHierarchyview.
Figure5‑8:Addinganewterraintothescene
Next,wewillpaintthisterrain:
SelecttheTerrainintheHierarchywindow.
Checkthatthesizeoftheterrainis500by500:clickontheterrainSettingsbutton,as
highlightedonthenextfigure.
Figure5‑9:Selectingtheterrain’ssettings
ScrolldowntothesectioncalledResolutionandcheckthattheterrain’sWidthand
Lengtharesetto500.Thisisimportantsothattheimagethatwehavecreatedforthe
outlinecanmatchtheterrainperfectly.
Figure5‑10:Checkingtheterrain’swidthandheight
IntheInspectorwindow,clickonthePainttoolfortheterrain,ashighlightedonthenext
figure.
Figure5‑11:SelectingthePainttool
Then,clickonthebuttonlabeledEditTexture,andselectAddTexturefromthe
contextualmenu:thiswillmakeitpossibletoeditthetexturetobeappliedontheterrain.
AnewwindowcalledAddTerrainTexturewillappear.
Figure5‑12:Selectingatexture
ClickontheSelectbutton,totheleft,fortheAlbedo(RGB).
Anewwindowwillappearinwhichyoucansearchforandselectthetexture
gameMapOutdoors.
Typethekeywordgameminthesearchfield,andthenclickonthetexture
gameMapOutdoorsonceitappearsinthesearchresults,asdescribedonthenextfigure.
Figure5‑13:SelectingthegameMapOutdoorstexture
Oncethisisdone,youwillbebacktothepreviouswindow;itwillshowthatthetexture
hasbeenselected.
Setthesizeofthetexturetomatchthesizeoftheterrain:setthexandyvaluesto500.
Thiswillmatchexactlythesizeoftheterrain.
Figure5‑14:Settingthesizeofthetexture
ClickonthebuttonAdd.
UsingthePainttool(i.e.,thetoolcurrentlyselected),clickonceontheterraininthe
Sceneviewtoapplythisoutlinetotheterrain.
Atthisstage,thetexturehasbeenappliedandtheSceneviewshouldlooklikethe
followingfigure.
Figure5‑15:Overviewoftheislandwithatexture
Givingdepthtotheterrain
Sofar,wehavemanagedtoapplytheoutlineoftheisland,andthat’sgreat.Itisnowtime
toaddsomedepthtotheterrain.
Makesurethattheterrainisselected.
SelectthePaintHeighttoolfromtheInspectorwindow,ashighlightedonthenext
figure.
Figure5‑16:SelectingthePaintHeighttool
Withinthesametab,intheSettingssection,settheHeightto5.
ThenpressthebuttonlabeledFlatten.
Figure5‑17:Flatteningtheterrain
Flatteningtheterrainwillraisetheentireislandandensurethatwecancarveorraise
portionsofit.Thisstepisimportanttobeabletocreateanyhillsorvalleysonthe
island.Ifyouareunsuccessfulinraisingtheterrainlateron,thiscouldbedueto
missingthisstep.
Atthisstagewearereadytocarveintotheterrain;oneofthefirstthingswewilldoisto
carvetheoutlinewherethereiswater,asthewaterlevelshouldbebelowthegroundlevel.
Let’sswitchtoamoreconvenientviewsothatwecanseethescenefromthey-axis:
locatetheGizmointheSceneviewandclickonitsy-axis;thisshouldswitchtheview
accordingly.
Figure5‑18:Theislandviewedfromthey-axis
Youmightaswellzoom-inonthebottomrightcorneroftheterrainusingsuccessively
themousewheelandthePantool(PressQ+draganddrop).
Figure5‑19:Zooming-inonthesoutheastcoast
Then,afterensuringthattheterrainobjectisselected,gototheInspectorwindow,and
selecttheRaise/LowerTerraintool,asindicatedinthenextfigure.
Figure5‑20:SelectingtheRaise/LowerTerraintool
IntheSceneview,PresstheSHIFTkey,starttodraganddropyourmouseontheblue
areaandmodifythebrushsizeto36ifnecessary(tocoverawiderarea).Asyoudoso,
youwillnoticechunksoftheterraindisappearing,revealingthescenegridlinesas
describedinthenextfigure.BypressingtheSHIFTkeyyoucanlowertheterrain;ifyou
omittodoso,dragginganddroppingthemousewillhavetheoppositeeffect.Somake
sureyoukeeptheSHIFTkeypressedfortheseactions.
Figure5‑21:Loweringtheterrain
Carryonuntilyouhavecoveredmostofthewaterareaaroundtheisland.
Onceyouhavecompletedtheentireoutlinefortheisland,wecansmoothouttheedgesto
makeitlookabitneaterandpolish-upourwork.
AfterensuringthattheTerrainobjecthasbeenselected,selecttheSmoothHeighttool
fromtheInspector,ashighlightedonthenextfigure.
Figure5‑22:SelectingtheSmoothHeighttool
Selectthesecondbrushfromtheleft-handside,andsetthebrushsizeto36.Youcan
alsouseothersettingsifyouwishtoexperiment.
Figure5‑23:Adjustingthepropertiesofthebrush
Afteradjustingthesesettingsyoucanapplythebrushtotheedgescreatedfromthe
previoustool,andyouwillnoticethatthesearenicelysmoothedout.
Figure 5‑24: The island before the Figure 5‑25: The island after the
Smoothtool
Smoothtool
Addingwater
Atthisstage,theoutlinehasbeenappliedandtheboundarybetweentheislandandthe
waterisclearlydefined.Sowecannowintroducethewaterasset.Inthenextsteps,we
willsuccessivelyaddthewaterassettothesceneandadjustittoensurethatthesceneis
realistic:
IntheProjectwindow,gotothefolder:StandardAssets|Environment|Water|Water|
Prefabs.
Figure5‑26:Locatingtheprefabforthewater
Onceyouhavelocatedthisfolder,youshouldseetwoprefabs(bluecubes)within.
WewillbeusingtheprefablabeledWaterProDaytime:draganddropthisprefabtothe
Sceneview;thiswillcreateanewobjectinthescene(WaterProDaytime).
UsingtheMovetool,movethewaterobjecttothecenterofthemap:becauseinthis
particularcase,wejustwanttomoveitalongthex-andz-axes,youcaneitherdragthese
individuallyordraganddropthegreenareadefinedbythesetwoaxes,thiswillensure
thattheobjectismovedonlyalongthex-andz-axes(i.e.,theobjectwillbemoved
horizontally).
Figure5‑27:Addingwater
Scale-upthisobjectonthex-andz-axesby500(i.e.,xandzscalepropertiessetto500)
Movethisobjectupsothatitappearsattheboundarythatyouhavejustsmoothed-out
previously(seetheboundaryhighlightedonthenextfigure):thiswilltakesome
readjustingandyoudon’tneedtohaveitrightthefirsttime.Infact,ifsomebluecolor
(fromthetextureoftheground)stillappearsabovethewater,wewillbeabletoeraseit
lateron,andreplaceitbyatexturethatissimilartothesandinstead.
Figure5‑28:Identifyingtheboundarybetweenthewaterandthesand
Addingtrees
Nowthattheoutlinehasbeencompletedandthewateradded,itistimetoaddsomemore
lifetotheisland,includingtreesandfoliage.Inthenextsteps,wewilllearnhowtoadd
treestotheterrain.
AfterselectingtheterrainobjectintheHierarchyview,selectthetoollabeledPlace
Trees,asdescribedonthenextfigure.
Figure5‑29:SelectingthePlaceTreestool
ScrolldownwithintheInspectorwindow.
IntheTerrainsection,clickonthebuttonlabeledEditTrees,andthenselectAddTree
fromthecontextualmenu.
Figure5‑30:Editingthetrees
ThisshouldopenanewwindowlabeledAddTree.
Weneedtoselectthetypeoftreetobeaddedastherearenoneselectedatpresent.
ClickonthebuttontotherightofthelabelNone(GameObject),ashighlightedonthe
nextfigure.
Figure5‑31:Assigninganewtree
Anewwindowwillappearsothatyoucansearchforandselectaparticulartypeoftree.
Inthisnewwindow,typethewordpalminthesearchfieldlocatedatthetopofthe
window;UnityshouldfindatexturecalledPalmDesktop,asillustratedonthenextfigure.
Figure5‑32:Assigninganewtree(continued)
Clickonthistexture,thiswillselectthetreeandtakeyoubacktothepreviouswindow.
Figure5‑33:Assigninganewtree(continued)
YoushouldseethatPalm_DesktophasbeenselectedastheTreePrefab;inotherwords,
wewillbeabletoaddtreesbasedonthetypeortemplate(orprefab)Palm_Desktop.
WecannowclickonthebuttonAdd.
YoushouldnowbeabletoseethatanewtypeoftreehasbeenaddedtotheTerrain.
Figure5‑34:Checkingavailabletreestobeaddedtotheterrain
Atthisstage,wearealmostreadytoaddtreestotheisland.Beforeyoudoso,youcould
modifysomeofthesettingssuchasTreeDensityorTreeHeight(ordosoatalaterstage).
IntheSceneview,locatethegreencirclesthatcorrespondtothelocationofthetrees.
Clickonthese(youcanalsodragthemouse)toaddtrees.
Figure5‑35:Addingtreestotheisland
Ifyouwanttoaddmoretreesinonego,youcanincreasetheTreesDensityparameter,
andthiswillspeed-uptheprocess.
Ifyouneedtodeletetrees,justpresstheSHIFTkeyasyoudragthemouse.
Proceedtotherestoftheislandandaddtreesintheareasdelimitedbygreencirclesor
anyotherlocationofyourchoice.
Trydifferentheightsforthetreestoseehowthesettingsforthetreesaffecttheir
appearance.
Afteraddingafewtrees,wecannowhavealookatthescene,andnavigatethroughit.To
doso,wejustneedtoaddacontrolleraswehavedoneinthepreviouschapters:
IntheProjectview,gotothefolder:Assets|StandardAssets|Characters|
FirstPersonCharacter|Prefabs.
LocatetheprefablabeledFPSController.
Draganddropthisprefabonthescene.
ThiswillcreateanewobjectcalledFPSController.
Figure5‑36:Addingafirst-personcontroller
Youcanthenadjustthepositionofthisobjectsothatitisslightlyabovetheground,and
playthescene.Thesceneshouldlooklikethefollowing.
Figure5‑37:Walkingaroundtheisland
Paintingtheislandwithrealistictextures
Atthispoint,thewaterhasbeenadded,alongwithtrees.Thisbeingsaid,whilethe
originaldesignisgreat,itwouldbegoodtobeabletopainttheterrainusingadditional
texturesorevenerasesomeofthegreencirclesorothertexturesincludedintheoutline.
Thankfully,UnityincludesaPainttoolthatmakesitpossibletoliterarilypaintonthe
terrainusingeitherbuilt-intextures(e.g.,rock,dirt,etc.)ortexturesthatyouhavealready
imported.Forpainting,wedisposeof,asforothertools,awiderangeofbrushes,andwe
canalsoadjustitssettings(e.g.,opacity).Solet’sjazz-upthelookoftheislandandadd
sometexturestoit:
SelecttheTerrainobjectintheHierarchyview.
IntheInspectorwindow,selectthetoollabeledPaintTexture,asillustratedonthenext
figure.
Figure5‑38:SelectingthePaintTexturetool
Again,wewillneedtoaddaparticulartexturetothispaintbrush;asaresult,wewillclick
onthebuttonlabeledEditTexture,andthenontheoptionAddTexturefromthe
contextualmenu.
Asforpreviously,clickonthebuttonlabeledEditTexture,andselectAddTexturefrom
thecontextualmenu:thiswillmakeitpossibletoeditthetexturetobeappliedonthe
terrain.
AnewwindowcalledAddTerrainTexturewillappear.
Figure5‑39:Selectingandaddingatexturefortheterrain
ClickontheSelectbuttonfortheAlbedo(RGB).
Anewwindowwillappearinwhichyoucansearchforandselectthetexture
GrassRockyAlbedo(clickonceonthetexture).
Figure5‑40:Selectingandaddingatexturefortheterrain
Oncethisisdone,youwillbebacktothepreviouswindow;itwillshowthatthetexture
hasbeenselected.
Youcankeepthedefaultvaluesforthesizeofthetexture(i.e.,15by15).
ClickonthebuttonAdd.
IntheInspectorwindow,youshouldnowseethatthetexturehasbeenaddedtothe
availabletexturesfortheterrain.
Figure5‑41:Selectingthenewtexturetopaint
Asforpreviously,wecanadjusttheBrushSizeandOpacity.Ihavesetmysettingsto17
and100respectively,butIinviteyoutoexperimentandseewhatworksbestforyou.
Finally,select(i.e.,clickon)thetextureofyourchoiceintheInspectorwindow,inthe
sectionTextures,sothatthetextureisappliedtothebrush.
Dragthemouse(i.e.,left-clickandmove)aroundtheareawhereyouwanttoapplythis
textureintheSceneview.
Figure5‑42:Applyingatexturetotheterrain
Atthisstage,youcanstartpaintingotherareasontheisland;wecouldalso,forexample,
erasepartsoftheisland,thatwewouldliketoamend.YoucanofcourseuseCTRL+Zto
undoanyofyourpreviousactions;however,ifyouwouldliketoremoveanimageoran
itemthatispartoftheoutlinemap,youcanproceeddifferentlybyerasingorpaintingover
itusingthecolorofthesand.Thiscanbedoneeasilyasfollows:
Locatethefilesandy_color.jpginyourfilesystem(i.e.,whereyouimportedthe
necessaryassetsforthischapter).
Importthefilesandy_color.jpgintoyourprojectbydragginganddroppingthisfilefrom
yourfilesystem(e.g.,explorerorFinder)totheAssetswindowinUnity.
Oncethisisdone,selecttheTerrainobjectintheHierarchyview.
Repeatthestepsperformedintheprevioussectiontoaddthistexturetothelistof
availabletexturesforthePaintTexturetool.
Oncethisisdone,selectthesandtexturetopaint,asillustratedonthenextfigure.
Figure5‑43:Selectingthesandytexturetoerasepartsoftheisland
StarttopaintovertheTerrain,forexampleonthepath,andyoushouldnoticethatit
disappearsprogressively,asillustratedonthenextfigure.
Figure5‑44:Applyingthesandytexture
Usingthismethod,youcandeleteanyofthetexturesintroducedbythemapoverlay.
Figure5‑45:Beforeerasing
Figure5‑46:Aftererasing
Afterdeletingsomeoftheoriginalpath,youcanthenapply,instead,texturesthatyou
havealreadydefinedinUnity.
Figure5‑47:Applyinganewtexturetothepath
AddingFoliage
Inadditiontocreatingtrees,Unityalsomakesitpossibletoaddfoliage(e.g.,plants),that
increasetherealismofyourscene.Theycanbe,asforthetrees,includedusinga
correspondingtool.Let’saddsomefoliagetothescene:
SelecttheTerrainobjectintheHierarchyview.
IntheInspector,intheTerrainsection,selectthePaintDetailstoolasillustratedonthe
nextfigure.
Figure5‑48:SelectingthePaintDetailstool
InthesectioncalledDetails,clickonthebuttonlabeledEditDetails,andthenselectthe
optionAddGrassTexturefromthecontextualmenu.
Figure5‑49:Addingthetextureforthegrass
AnewwindowlabeledAddGrassTexturewillappear;asyouwillsee,notexturehas
beenselectedyet,sowewilllookforandselectatextureforourfoliage.
ClickonthebuttontotherightofthelabelNone(Texture2D)asdescribedonthenext
figure.
Thisshoulddisplayasearchwindow:enterthetextgrassinthesearchfieldandthen
selectthetexturelabeledGrassFrond02fromtheresults.
Oncethisisdone,anewwindowwillappear,thistimewiththetexturethatyouhave
selected.
PressAddtoaddthistexture.
Thefullprocessissummarizedonthenextfigure.
Figure
5‑51:
Figure 5‑50: Adding a
Adding a texture Figure 5‑52: Adding a
textureforthegrass(step
for the grass (step textureforthegrass(step3)
1)
2)
Atthisstage,thenexttextureshouldappearinthesectionlabeledDetails.
Youcannowaddfoliagetotheisland.Ihaveusedthefollowingsettings(butfeelfreeto
experimentwithdifferentvalues):Brushsize=20,Opacity=1,TargetStrength=0.8
Figure5‑53:Aportionoftheislandwithfoliagefromthesceneview
Onceyouhavecompletedyourmodificationsonpartsoftheisland,playthesceneand
observethefoliage.
Figure5‑54:Aportionoftheislandwithfoliagefromthegameview
Addingalakeandamountain
Intermsofrealism,wehavemanagedtoaddsomeprettyinterestingfeatures,including
trees,foliage,water,andtextures.Oneofthelastelementsthatweneedtoaddisthelake
thatislocatedinthemiddleofthemapaswellasamountain.Forbothelements,wewill
needtoeithercarveintotheterrain(tolowertheterrain)orraisetheterrain,andwewill
beusingthetoolRaise/LowerTerrainforthispurpose.
SelecttheTerrainobjectintheHierarchyview.
Pantheview(CTRL+Q)sothatthelakeappearsinthemiddleoftheview.
Figure5‑55:Locatingthelake
IntheInspectorwindow,selecttheRaise/LowerTerraintool(firsticonfromtheleft).
Ifyouarenotsureaboutthenameoftheiconslocatedinthetoolbarfortheterrain,you
canmovethemouseoveranyoftheseicons,andatooltip(i.e.,contextuallabel)will
displaythenameofthecorrespondingtool.
Selectthethirdbrushfromtheleft.Thissizeshouldbeappropriatetocarvethelake,but
feelfreetouseotherbrushesiftheyworkbetterforyou.
Selectabrushsizeof51andsettheopacityto84.
PresstheSHIFTkey,left-click(i.e.,pressthemouse’sleftbutton),andthendragyour
mouse(i.e.,move)ontopoftheblueareathatdefinesthelake.
Figure5‑56:Definingthelake
UsingtheSmoothHeighttool,smoothouttheboundaryofthelake.
SothatwecanobservethisareawiththeFirst-PersonController,movetheFirst-Person
Controllerclosetotheboundaryofthelakeandplaythescene.
Figure5‑57:Lookingatthelake
Oncethisisdone,wewillnowcreateasimplehillusingthesametool;wewillbe
creatingahillclosetothelakeintheareahighlightedonthenextfigure.
Figure5‑58:Locatingthepositionofthehill
Youcanstoptoplaythescene.
IntheInspectorwindow,selecttheRaise/LowerTerraintool(firsticonfromtheleft).
Selectthethirdbrushfromtheleft.Thissizeshouldbemostappropriatetocarvethe
lakebutfeelfreetouseotherbrushesifitworksbetterforyou.
Selectabrushsizeof51andsettheopacityto84.
ClicktheLeftMouseButton,andthendraganddropthemouseontopofthebluearea
thatweidentifiedearlier,asperthenextfigure.
Figure5‑59:Creatingahill(part1)
Figure5‑60:Creatingahill(part2)
Afterthesemodifications,youcanpanyourviewtocheckthatyouhavemanagedtoraise
thegroundproperly,anditshouldlookasfollows(althoughthiscouldtakemany
iterations,soit’sperfectlyokifitdoesnotlookexactlylikethenextimage).Also,
rememberthatyoucanundoyouractionsusingCTRL+Z,ifneedbe.
Figure5‑61:Viewingthehillfromabove
Atthisstage,wejustneedtoapplyatexturetothemountaintomakeitlookmore
realistic.Asfortheground,wewillbeusingthepainttoolafterselectinganappropriate
texture:
SelecttheobjectlabeledTerrainintheHierarchyview,andusethefollowingsettings:
brushsize=51,Opacity=84,TargetStrength=1.
Selectthefourthbrushfromtheleft.
SelectthetoolPaintTextureaswellasthesecondtextureinthelist(i.e.,GrassFrond02),
asdescribedonthenextfigure.
Figure5‑62:SelectingandusingthePaintTexturetool
Youcannowpaintthehill;youcaneitherkeepthedefaultviewintheSceneviewor
switchtoatop-downviewbyclickingonthey-axisofthegizmo.
Topainttheborderofthemountain,youcanusedifferentsettingsforthebrush(e.g.,
Opacity=64).
Onceyouhavefinishedpaintingthehill,itshouldlookliketheoneillustratedonthe
nextfigure.
Figure5‑63:Thehillviewedfromabove
PlayyourscenetoseehowthehilllookslikeintheGamewindow.
Figure5‑64:Thehillviewedinthegameview
Ofcourse,thehillthatyouhavecreatedmaylookslightlydifferent,andthatisperfectly
ok.
NotethatyoucanalwaysundoanyofyourdesignusingCTRL+Zorbyloweringthe
areasthatyouhavepreviouslyraised(bypressingtheSHIFTkeywhenusingthe
Raise/LowerTerraintool).
Addingacartothe3Denvironment
Soatthisstage,wehaveagreatenvironmentwithtrees,foliage,water,andhills.
However,duetothesizeoftheisland,itmaybemoreconvenientfortheplayerto
navigateusingacarratherthanwalking.Luckily,Unityincludesasetofbuilt-in
vehiclesthatarereadytobeusedwithouttoomuchtweaking,exceptfromtheadditionof
acamera.Inthissection,wewilldiscoverhowwecanimportandincludetheseassetsinto
ourscene.First,let’simporttheVehiclespackage:
InUnity,select:Assets|ImportPackage|Vehicles.
AnewwindowlabeledImportPackagewillappear.
ClickonImporttoimportalltheassetswithin.
Oncetheprocessiscomplete,wecancheckthatthesehavebeenimportedproperlyby
goingtothefolderAssets|StandardAssets|Vehicles,andcheckingthatitincludesboth
thefoldersAircraftandCar,asdescribedonthenextfigure.
Figure5‑65:Folderscreatedforthevehicles
GotothefolderAssets|StandardAssets|Vehicles|Car|Prefabsanddraganddropthe
assetlabeledCarfromitsfolderontotheSceneview,neartheFirst-PersonController.
Figure5‑66:Addingthecartotheenvironment
Becausewehavetwocontrollersinthescene,wewilltemporarilydeactivatetheFirstPersonControllersothatusingthearrowkeysonthekeyboardonlymovesthecar,and
wewillalsoensurethatthecarisnowthetargetof(orisfollowedby)themaincamera.
Firstlet’sincludeanewcamerathatfollowsthecar:
GotothefolderAssets|StandardAssets|Cameras|Prefabs.
SelecttheprefabFreeLookCameraRiganddraganddropittotheScene(orthe
Hierarchy)view.
Figure5‑67:Addingacameratothescene
Thensetthecarasthetargetforthiscamerabydragginganddroppingtheobjectlabeled
CartotheTargetattributeofthecamera,asdescribedonthenextfigure.
Figure5‑68:Settingthetargetforthemovingcamera
Then,wewilldeactivatetheFirst-PersonControllersinceitwillnotbeusedfor
navigation.Todoso,selecttheFirst-PersonControllerinthesceneand,usingthe
Inspectorwindow,deactivatethisobject(unchecktheboxasillustratedonthenext
figure).
Figure5‑69:DeactivatingtheFPSController
Andlast,wewillalsodeactivatethemaincamera,usingthesametechnique;usingthe
Inspectorwindow,deactivatethisobject(i.e.,unchecktheboxasillustratedonthenext
figure).
Figure5‑70:Deactivatingthemaincamera
Oncethisisdone,youshouldbeabletoplaythescene,andseethecarmovingasyou
pressthearrowkeys(i.e.,up,down,leftandrighttorespectively,accelerate,decelerate,
turnleftorturnright).
Figure5‑71:Drivingthecar
Addinganaircrafttotheenvironment
Asmentionedearlier,Unityoffersseveraltypesofvehicles,includingacarandan
aircraft.Inthissection,wewillfocusonaddingandpilotinganaircrafttoflyoverthe
islandandseeitfromthesky.
Firstlet’saddtheaircraft:
InUnity,gotothefolderAssets|StandardAssets|Vehicles|AirCraft|Prefabsanddrag
anddroptheassetlabeledAircraftJetfromitsfolderontotheSceneview,neartheFirstPersonController.
Figure5‑72:Addingtheaircrafttothescene
Then,wewilldeactivatetheobjectlabeledCarsincewewillnotbeusingitfor
navigation.Todoso,selecttheCarintheSceneviewand,usingtheInspector,deactivate
thisobject(unchecktheboxasillustratedonthenextfigure).
Figure5‑73:Deactivatingthecar
Finally,wewillsettheaircraftasthetargetfortheactivecamerabydraggingand
droppingtheobjectlabeledAircraftJettotheTargetattributeoftheactivecamera(i.e.,
FreelookCameraRig),asdescribedonthenextfigure.
Figure5‑74:Settingtheaircraftasthetargetofthecamera
Oncethisisdone,youshouldbeabletoplaythescene,andpilottheaircraftbypressing
thearrowkeysonyourkeyboard(downarrowtogoup).
Figure5‑75:Pilotingtheaircraft
Addingonboardcamerastotheaircraft
Intheprevioussection,whilewehavemanagedtoaddandpilottheaircraft,the
cameramaysometimesnotbefastenoughtofollowtheaircraft;also,itwouldbegreatto
seethevirtualworldfromwithinthecockpitorasifyouwerelookingdown.Toachieve
this,wewillsuccessivelyaddtwocameras:onethatisinthecockpitandthatlooks
forward,andanothercamerathatlooksdownandthatrevealsaviewoftheislandfrom
thesky.
Let’saddthefirstcamera:
Createanewcamera:selectGameObject|Camerafromthetopmenu.
ThiswillcreateanewobjectlabeledCameraintheHierarchyview.
DraganddropthiscameraatoptheobjectAircraftJetobject.Thisway,thecamerais
nowachildoftheplane.Inotherwords,anytransformationappliedtotheplanewillbe
appliedtothecamera;soastheplanewillbemoving,sowillthe(embedded)camera.
Figure5‑76:Settingthecameraasa Figure 5‑77:Thecameralisted as a
childoftheaircraft
childoftheaircraft
Youcanthenrenamethiscamera,forexample,from_plane
Whenthisisdone,weneedtochangethepositionofthecamerasothatitislocatedatthe
frontoftheplane,insidethecockpit.
Thepositionofanychildobjectisusuallyprovidedinrelationtoitsparent.For
example,iftheparentisattheposition(4,5,6)andthechild’spositionis(1,0,0),it
meansthatthechildisattheposition(1,0,0)inrelationtotheparent.Inotherword,its
relativepositionis(1,0,0)butitsabsoluteposition(inthegameenvironment)is(4,5,6)
+(1,0,0)whichis(5,5,6).
Withthisinmind,wecanchangethepositionofthecamerato(0,1.5,7.0)asillustratedin
thenextfigure.
Figure5‑78:Positioningthecamerawithintheaircraft
Toensurethatthecameraispositionedproperly,wecanchecktheviewfromthiscamera
inthebottom-rightcorneroftheSceneview.
Figure5‑79:Checkingthepositionofthecamera
Beforewecanplaythescene,wewillneedtodeactivatethecamerathatwehaveusedso
far(FreeLookcameraRig)usingtheInspectorwindow.
Figure5‑80:Deactivatingthecurrentcamera
Asweplaythesceneandtakeofffromtheisland,wecanseetheviewfromthecockpitas
describedinthenextfigure.
Figure5‑81:Theviewfromthecockpit
Thelastchangeweneedtoapplynowistheadditionofacamerathatlooksdownfrom
theairplane;forthispurpose,wecanusethesameprincipleaspreviously,bycreatinga
newcamera;theonlydifferenceisthatwewilldisplaytheimagecapturedbythiscamera
atopthecurrentview(i.e.,similartoanadditionalscreeninthecockpit).
Let’saddthesecondcamera:
Createanewcamera:SelectGameObject|Camerafromthetopmenu.
ThiswillcreateanewobjectlabeledCameraintheHierarchyview.
DraganddropthiscameraatoptheobjectAircraftJet.
Renamethiscameralooking_down.
Selectthisobject(i.e.,looking_down).
IntheInspectorwindow,locatetheTransformsection:changethepositionofthisobject
to(0,0,0)andtherotationto(90,0,0):thisrotatesthecameraaroundthex-axisabout90
degreessothatitisorienteddownwards.
IntheInspectorwindow,locatetheCameracomponentforthisobject.Inthesubsection
labeledViewPortRect,changethesettingstoW=.3andH=.3.Keepthexandysettings
to(0,0).
IntheDepthsubsection,enterthevalue2.
TheViewPortRectdescribeswheretheimagecapturedbythecamerashouldbe
displayed.Thisimageisdisplayedinarectangledefinedbyitsposition(x,y)andsize
(widthandheight).Thewidthandheightarerepresentingapercentageofthescreen
(e.g.,1for100%).Thexandycoordinatesdefinethebottom-leftcornerofthe
rectangle,with(0,0)beingthebottomleftcorneroftheSceneview.Allcamerasalso
haveadepth,andthecamerawiththehigherdepthisdisplayedontopofcameraswith
lowerdepths.Inthisexample,becauseothercamerashaveadepthof0bydefault,the
imagecapturedbythiscamerawillbedisplayedontopoftheimagescapturedbythe
othercameras,andcanthereforebeseenaspartoftheinterface.
Asyouplaythesceneandtakeofffromtheisland,youshouldseetheshadowofthe
aircraftonthewater,capturedbythesecondcamera,displayedinthebottom-leftcornerof
theview,asillustratedonthenextfigure.
Figure5‑82:Viewfromthesecondembeddedcamera
Notethattohavethetimetoseethegroundfromthesecondcamera(i.e.,embedded
cameralookingdownwards),wecouldcreateotherislandsbyduplicatingtheTerrain
severaltimes,andmovingtheduplicatesalongthez-axis,asillustratedonthenext
picture.
Figure5‑83:Duplicatingtheisland
Asyouplaythescene,youwillhavemoretimetoseetheislandsfromthecameralabeled
looking_down.
Figure5‑84:Seeingtheislandsfromthecockpit
Addingbuildingstotheisland
Wehave,atthisstage,addedallthenecessaryelementstoourisland,basedonouroutline,
exceptfromthebuildings.Thesecanbecreatedveryeasilyusingthesametechniques
coveredinthepreviouschapters,asyouwillneedto:
Createnewboxes.
Placeandresizetheseboxessothattheycovertheblackareasontheoutline.
Scaletheseboxesonthey-axis,usingaheightofyourchoice(forexample40).
Finally,wecanaddatexturetothebuildings.Asforpreviously,youcanimportatexture,
fromtheresourcespreviouslydownloaded,calledbuildings.jpg,andthendraganddropit
ononeofthebuildings.Youcanthenmodifythetilingforthistextureto(1,5)by
accessingitscorrespondingmaterial.Thisbeingsaid,youcanuseanytextureofyour
choice,includingthetexturethatyouhavealreadyappliedtothetilesfortheindoor
environment.
Figure5‑85:Addingbuildingstothefirstisland
Whilewehaveonlycreatedthebuildingsforthefirstisland,youcaneasilyduplicate
themtwiceandpositiontheduplicatesonthetwoadditionalislands.Afteraddingthe
buildings,youcanplaythesceneandcheckhoweachofthemlookslikebyeither:
Walkingaroundtheislandafterdeactivatingallcharacterandvehiclecontrollers(except
fortheFirst-PersonController)aswellasthecameraFreeLookCameraRigthatfollows
thesecontrollers.
Drivingaroundtheislandbydeactivatingallcontrollers(exceptfortheCar),and
activatingtheFreeLookCameraRigcameraandsettingitstargetaccordingly.
Flyingaroundtheislandbydeactivatingallcontrollers(exceptfortheAircraftJet).
Figure 5‑86: The island with a Figure 5‑87: Walking around the
building
island
Levelroundup
Summary
Inthischapter,wehavebecomemorecomfortablewiththecreationofindoorandoutdoor
environmentsandwelearnedhowtouseUnity’sbuilt-inassetstocreateanimpressive
environment.WedelvedintothedifferenttoolsavailableinUnitytocreate,transformand
texturebasicshapes.Well,fromfindingyourwayaroundUnitytocreatingarealistic
island,youcanseethatyouhavealreadymadesomeconsiderableprogresssincethestart
ofthebook.Youhavemanagedtocombineyourskills,yetwithnoprogramming
knowledge,tocreateatrulyrealisticandinteractiveenvironment.
Quiz
Itisnowtimetotestyourknowledge.Pleaseanswerthefollowingquestions(e.g.,Yesor
No).Theanswersareavailableonthecompanionwebsite
(http://www.learntocreategames.com/learn-unity-ebook).
1.Aviewportisacircularareathatdefineswherethecontentcapturedbyacamerawill
bedisplayedonscreen.
2.Thepositionofachildobjectisalwaysdeterminedbasedonthepositionoftheparent.
3.Onceaterrainhasbeencreateditcan’tbemodified.
4.Itispossibletocreateamountain(hill)withUnity.
5.Itisnecessarytoflattenaterrainbeforeraisingorloweringanyareawithin.
6.ThepackagecalledEnvironmentincludesallnecessaryassetstocreatewaterandtrees.
7.Oncetreeshavebeencreatedtheycan’tberemoved.
8.Itispossibletocreateaterrainwithhillsandvalleysfromasimpleboxobject.
9.Thecontentofonlyonecameracanbedisplayedonscreen.
10.Thecontentofacameraalwaysfills-uptheentirescreen.
Checklist
Ifyoucandothefollowing,thenyouarereadytogoto
thenextchapter:
Createaterrain.
Raiseandlowerpartsoftheterrain.
Addfoliage,treesandwatertotheterrain.
Add(andtrack)acaroranairplanethatincludesan
embeddedcamera.
Combinetheoutputofseveralcamerasonscreen.
Challenge1
Forthischallenge,youwillneedtocreateanewoutdoorenvironment,basedonanew
templateasfollows:
ImportthetexturegameOutline2.pngfromthefoldersthatyouhavedownloadedfrom
thecompanionsite.
Createanewscene.
Applythesametechniquesasbeforetorecreatetheisland.
Addvehiclesofyourchoice.
Challenge2
Forthischallenge,youwillneedtocreateyourownoutline,usingtheimagemanipulation
toolofyourchoice,andthenapplyittocreateanewislandofyourowndesign!
Youcouldproceedasfollows:
Createanewimagewithasizeof500pixelsby500pixels.
Setthebackgroundtowhite.
Createtheoutlineoftheislandusingabrushofsize1.
Addgreen,blue,orbrownareastoidentifythepositionoftrees,water,orpaths.
Saveyourimageinthejpgorpngformat.
ImportthisimageintoUnity.
Createanewscene.
Usethisnewtemplatetocreateyounewoutdoorscene.
6
FrequentlyAskedQuestions
Thischapterprovidesanswerstothemostfrequentlyaskedquestionsaboutthefeatures
thatwehavecoveredinthisbook.
Navigation
HowdoInavigatethroughmyscene?
ImporttheCharactersassetsandaddoneofthebuilt-incontrollerstothescene.
AfterimportingmyFPSControllerandaddingittothescene,itlookslikeitisfalling
asIplaythescene.
MakesurethattheFPSControllerisabovethegroundwhenaddedtothescene.
AfterimportingmyFPSControllerIwalkaroundtheIslandbutIonlyseethescene
fromastaticcamera.
Makesurethatthemaincameraisdeactivated.
Aftercreatingmymaze,Icanstillseearoundmycharacteralthoughnolightsare
activeinthescene?
Makesurethatyouhavesettheambientlightforthescenetoanintensityof0(Window|
Lighting).
TransformationsandAssets
HowdoIimportassetsinmyscene?
Importtheasset(e.g.,texture,imageorsound)byselectingAssets>ImportAssets.For
textures,youthenjustneedtodrag-and-dropthetextureonyourobject.Youcanalsodrag
anddroptheassetsfromyourfilesystem(e.g.,explorerorFinder)intoUnity.
Wherearemyassetsstoredinmyproject?
Usually,assetsaresavedorimportedintheactivefolder.Soiftheactivefolder(theone
selectedintheProjectwindow)isAssets,thentheassetswillbeimportedinthisfolder
(exceptsformostofUnity’sbuilt-inassetsthatwillbe,bydefault,importedinthefolder
StandardAssets).
HowcanItransformobjects?
Youcanselecttheobjectandtheneitherusethekeyshortcuts(i.e.,W,E,R,andT)or
modifytheobject’stransformpropertiesintheInspectorwindow.
WhatisthedifferencebetweentheRecttoolandtheScaletool?
TheRecttoolwasintroducedinUnity5.Butbeforethen,ifyouscaledanobject,let’ssay
acube,itspositionwouldbechangedaswell.So,forexamplewhenyouweredesigninga
mazewithboxes,youwouldconstantlyneedtoscaletheboxes,andthenmovetheboxto
compensateforthescaletransformation.WiththeRecttool,allisalltakencareof,soas
youresizetheobjectwiththeRecttool,atleasttwoofitscornerswillremainatthesame
position.
Creating,OrganisingandSearchingforObjectsandAssets
HowdoIcreateanobject?
Select:GameObject|Add.
HowdoIaddatexture?
Importthetexture(Assets|ImportAssets)anddrag-and-dropittoyourobject.
HowdoIgroupobjects?
Createanemptyobject(parent)anddrag-and-droptheobjectstobegroupedontheparent.
HowdoIlookforobjectsinmyproject?
Usetheprojectsearchwindowandsearchbynameortype(e.g.,t:scene)
IfIimportanassetinmyproject,canIaccessitfromanyscenewithinthisproject?
Yes,andthat’saveryinterestingfeaturethatwillsavesomespaceonyourharddrive.
7
Thankyou
Iwouldliketothankyouforcompletingthisbook;Itrustthatyouarenowconfortable
withUnityandthatyoucancreateinteractive3Dgameenvironments.Thisbookisthe
firstinaseriesoffourbooksonUnity5,soitmaybetimetomoveontothenextbookfor
thebeginnerlevelwhereyouwilllearnmoreaboutscripting.Youcanfindadescriptionof
thisbookontheofficialpagehttp://www.learntocreategames.com/learn-unity-ebook.
Sothatthebookcanbeconstantlyimproved,Iwouldreallyappreciateyourfeedbackand
hearwhatyouhavetosay.So,pleaseleavemeahelpfulreviewonAmazonlettingme
knowwhatyouthoughtofthebookandalsosendmeanemail([email protected])
withanysuggestionyoumayhave.Ireadandreplytoeveryemail.
Thankssomuch!!