46Tips&Tricksfor2DmobilePerformanceinUnity.
[Link]
requiresalittlebitoftaming(andinsomecasessomeverycounterintuitivetrickery,butthatswhere
thismetaphorfallsapart).IvehadabitofastrugglegettingTruckTosstoplaysmoothlyonmy3GS,
butheresanicebiglistoftipstohelpyouonyourway.
IfthisisyourfirstjumpintotheworldofUnity,myfirsttip(thisonesafreebie)istostoptryingtouse
[Link],youwillbeaddingmultiple
scriptcomponents,[Link],myapproachwasto
largelyignoreprefabs(orusethemlikeFlashsdisplaylist)[Link]
asitistodeviate,getreadytoputinsomework!
Withoutfurtherado,letsgetstarted:Physics:
Usethebuiltinphysics.
Itmightseemlikeawasteofcyclestohaveafully3Dphysicsenginerunningtheshowfora2D
game,[Link]
talkingaboutahyperoptimisedenginemaintainedbylargeprofessionalteams,andnotahobbyist
[Link]/Yrotationforthat2Dfeel.
Trytousea1/1scale.
BythisImean,1unit=[Link],butyourelikelytoencounter
someweirdnesswhenitcomestocollisions,[Link],agrand
pianowithoutairresistancewillfallasfastasadeadbabybutifeverythingislarge,itwillseemslow.
Youcanfiddlewithgravity,butagain,[Link]
1/32scalecomparedtomyspriteswithacamsizeof160.
GetyourobjectMassright.
Justlikewithscale,ifyouhaveagrandpianoweighing2gmoradeadbabyweighing500kgthings
[Link].
Meshcolliderscanbeslowcomparedtoprimitivebox/spherecolliders.
Whileaspheremayhavemanymorevertsthansayacube,theuniformdistancefromthecentre
wouldmakeitmassivelyeasiertocalculatethanlotsofindividualtriangles.
Youcansimulatemorecomplexshapesbycombiningprimitivecolliders.
IfyouhaveaparentobjectwithsayaBoxColliderandRigidbodycomponent,youcanaddchild
[Link].
Continuingfromtheabove
Ratherthanhavingseveraloftheselinkedtogether,youcanaddmorechildobjectswithRigidBodies
andColliders,[Link]
forexamplewithaparentbodytomovetheentirething.
Multiplebasicjointsarenotsupportedononegameobject
[Link]
examplehaveaspringandasliderfromwheeltoaxlecuttingdownonasuspensionobjectin
between.
ObjectswithacolliderbutnoRigidBodyareconsideredstatic.
Movingtheseisexpensive,soifyourecreatingthemwithcode,addthecolliderandphysicsmaterial
(tothecollider)afterpositioning.
Whileitsconsideredgoodpracticetokeepyoursolveriterationsconstant
youmightfinditbeneficialtousethefullamountonlyevery2ndupdate.I.e.8,4,8,4,8,[Link]
alleviatessomeoftheprocessorloadthesolverforexamplemaynothavetoskipiterations,andwill
[Link].
WhiletheuseofInterpolationandExtrapolationonRigidBodiesisdiscouragedenmasse..
insomecasesyoumightfindthatturningtheseon,andreducingtheoverallsolveriterations
[Link].
Loweryourtimestep!
Ifyoureaimingforanunrealistic60FPSandthephoneisconstantlystruggling,yourebestjustto
settleforalowerframerateandgiveitsomebreathingroom.Iliketousea0.03fixedtimestepwitha
[Link],itcanbeslightlycounterintuitivedecreasingtimestepstogethigher
framerates,butgiveitashot.
Timescalescaling.
Thiscouldhelp,[Link]
[Link],especiallyifanobject
hastraveledsay,amileinoneframe,itsnotgoingtohitadamnthing.
Sprites&TexturesMyengineusesahybridsystemofSpriteManager2/EZGUIandRageSplinefor
sprites,butIveused2DToolkitandmuchofthefollowingstillapplies.
Easyonthefillrate!
Itmightseemobviousbutifyouhavea6464image,withonlythetopleft3232filled,thatsstilla
[Link].
Hidespritesyourenotusing.
Makeareferencetothemandsetthemactive=falseTheywontbedrawnwhenoffscreenanyway,
butsomethinghastodeterminewhetherornottheyrevisibleandchancesareyouknowbest,
especiallywhenonespritemaybefullyhiddenbehindanotherandisstilldrawn.
[Link].
Ifyouhave40collectablecoinsinyourlevel,allusingthesamespritethenbatchingwillusetheone
texturesourcemultipletimesonagiantmesh,[Link]=[Link]
rarecasesthebatchcalculationscanbeahinderance,dependingonhowyourgamessetup,butif
thatsthecase,chancesareyouredoinitwrong.
ResizeyourspritesQuad(thespriteitself)ratherthanitstransform.
IfyouhavesayaspritecomponentonaGameObject,thenresizetheGameObjectstransform,
[Link].WithSM2forexample,
youdjustsettheSprite/PackedSpritesWidthandHeightpropertiesintheinspector.
Ifyouhavea6464sprite,ona6pxwidecube
thenitsgoingtolooklikeasmallversionofyourimage,butuponzoomingin,youllseethatthefull
[Link].
Unlessyourezoominginandout,youmightnotwanttousesuchalargetexture.
UseaSpriteSheet/Atlaswherepossible.
Thisoneoughttogohigher,[Link]
itemslikeyourcharacter,coins,platforms,etcinasingleimage/[Link]?Lessdrawcalls!The
[Link]
weremodellingaredandwhitestripycandycane,youddrawonewhiteandoneredline,thenapply
[Link].
Usetherightshaders!
Theresnopointusinglitshadersifyouvenolighting,andtheresnopointusingatransparent
[Link],by
googlinganddoingalittlecopypastaviaMonoDeveloporusingthosethatcomewithSM2/[Link]
[Link]
mightbeeasytounderestimatetheimportanceoftheseevenina2Denvironment.
Doyoureallyneedantialiasing/filteringonyoursprites?
[Link]
monitor,[Link],andremembertoapply
changestoyourSpriteAtlaswherepossible.
Easyonthecompression!
DXT(DirectX)compressionwilldoafantasticjobonyourPC,withhardwaredecoding,butmobile
[Link]
deviceswillsupporthardwarePVRTCcompressionandAndroidsETC,andkeepinmindwhatIsaid
[Link],butyou
certainlydontwanttobedecompressingthemduringgameplay.
DoyouneedMipMaps?
[Link]
dependingonhowfarawayyouare,[Link]
memoryandmoredecompressiontime.Youprobablydontneedemfora2Dgame.
Conversely
ratherthanusinggiantspritesonanonretinadisplayandtinyspritesonaretinadisplay,itmight
beworthyourwhilemakingasmallandlargeversionoftexturesandusingeachaccordingly.
Read/Writeenabledtexturesgenerateasecondcopy.
[Link],youcanjustleavethisturnedoff.
Tintingaspritewillbreakbatching
[Link],ortrytopremake
anycolorsyoullneed![Link]..doitinphotoshop.
Loading,SavingandObjectAccess:DoyoureallyneedtorecreateyourGUIforeachlevel?
Youcanhideitandhaveitpersistwhenloadingdifferentscenes,reducingloadingtime.
[Link]()isslow!
Onecommontechnique(whichprovedabsolutelyvitalinTruckToss)istocreateapoolofobjects
[Link],disableitandshove
[Link]
MakePrefab(path/to/prefab)[Link]()providedtherearenonein
[Link]()isevenslower!
Thisfunctiondoesnotcache,[Link]
wantahybridpoolsystemifyouredoingalotofloading\[Link]
whichpreloadsobjects,butwhentheinstantiatefunctioniscalled,itkeepsadifferentcopyina
[Link]
thesparelist,[Link]
balancingactofmemoryuseandprocessoruse,[Link]()
andGetCompoenent()..
areslow(Yousawthatonecoming,right?).Ifyouregoingtobeusinganobjectorcomponent
repeatedly,thenitmakessensetocreateareferencetoitinalocalvariableratherthanlookingitup
[Link].
Reflectionistheabilityforalanguage\codetolookwithinitselfandgetmethodnames\types\scope
[Link],[Link]
[Link].
Ithastoscantreesofobjectslookingfororphanedclassesandobjects,andislandsofobjectswith
referencesonlytoeachother,determinehowlongtheyvebeenthatway,andthenfreeupthe
[Link],butthatsgenerallymoreofahinttoitthanacommand,and
[Link]
willcauseIOSdevicestocrash\[Link]
actuallysecondarytothepointthatwhenmemoryslow,yourgamewillslowdowndramatically,
especiallyduringgarbagecollectionsandwhenyouretryingtoinstantiatenewobjects.
Sounds:
SetyourBGmusictodecompressonload.
Anythingyoullbeusingalotshouldprobablybedecompressedonloadratherthanstreamingfrom
thedisk(whichisslowandcanbeespeciallytroublesomeonAndroid.)Thisisanothertradeoff
situationhowever,[Link]!
Infrequentlyusedclips
..maybeleftcompressedinmemory,especiallyiftherearelotsofthem.
Forcetomono?
Yesyes!Unlessyoureallywantstereoandyouvegotsomebitchinmusicorsoundeffects,youll
[Link]
Hardwaredecodingisfaster.
Well,thatsageneralisation,butfasterisbetter.
UI:
UnitysUIsystemisslow.
Wherepossibletrytouseapluginorspritepackagethatrenderstomeshesin3Dspace.
OnGUIisslow!
[Link],and
[Link].
TrytokeepyourUIanimationsinFixedTimestep()functions.
[Link]
havingallofyourgamelogicforeveryclassbranchoutformasinglebasecalltoFixedTimeStep()
DoesyourUIhavetoupdate*every*frame?
[Link]
toss,thegamerunsmuchsmootherwiththeentiretyofthegamelogicrunningoneverysecond
[Link],right?
MoarCameras!
Ifyourgamedoesalotofscaling\zooming,thenwhyhavetoscaletheUIandriskbreaking
batching?AddanothercamerafortheUI,[Link],it
soundslikealotofextrablitting,butcouldpotentiallyspeedyourgameupwithverylittleinthewayof
changes.
BuildOptions:
Disabletheaccelerometer!
InolderUnities,thatwasdonevia#definekaccelerometer_frequency0intheAppControlerclassvia
[Link],andcanfreeup23FPS.
InsomecasesOpenGLES1.0or2.0
[Link]\iOS.
Tryonasmanydevicesasyoucan.
Stripthingsdown!
Whenyourgamesrunningniceandstable,switchcompatibilitytothe.NET2.0subset,Stripping
[Link]
[Link]
[Link].
TargetiOS5wherepossible.
[Link],makesureyourXCodeprojectssettings
match,[Link].
BonusContentBuildingFaster!:
SymlinkUnityLibraries
fromthebuildsettingswherepossible,thiswillsavecopyingmorefilesovertoxCode,by
[Link].
SetyourDebugInformationFormat
FromwithinXcode(BuildSettings)toSTABS,otherwisehavefunwatchingDWARFtakingages.
Stabs..dwarfLols
SometimesusingBuildfor
[Link].
Ihavenoideawhythisisso,butyourewelcome.
BonusContent2Fasterphysicsmodelling:ThisisafunlittletechniqueIusetoconvertedge
chainstosolidblocks!Createafakeedgechain,whereeachlinkbetween2pointsisactuallya
stretchedout,rotatedcubeparentedtosomething,formingtheoutlineofshapeofyourchoice
(cloud\star\car\whatever).Hitplay,andwhilethegameisrunning,dragyourchainbackintothe
[Link].
Thisletsyouuseyourowncodetogeneratephysicsshapes.
Andfinally,
[Link],[Link]
somethingseemslikeasillyideaatfirst,youmightjustnothavethoughtaboutitfromallangles.
[Link]!