0% found this document useful (0 votes)
8K views6 pages

46 Tips for Optimizing Unity 2D Mobile

This document provides 46 tips for optimizing 2D mobile game performance in Unity. Some key tips include using Unity's built-in physics engine instead of a separate 2D engine, keeping object scales and masses realistic, batching sprites from the same texture together, using sprite sheets to reduce draw calls, choosing optimized mobile shaders, and reducing texture sizes and compression to improve load times. Proper use of physics, sprites, textures, and memory management are emphasized to improve frame rates on mobile devices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8K views6 pages

46 Tips for Optimizing Unity 2D Mobile

This document provides 46 tips for optimizing 2D mobile game performance in Unity. Some key tips include using Unity's built-in physics engine instead of a separate 2D engine, keeping object scales and masses realistic, batching sprites from the same texture together, using sprite sheets to reduce draw calls, choosing optimized mobile shaders, and reducing texture sizes and compression to improve load times. Proper use of physics, sprites, textures, and memory management are emphasized to improve frame rates on mobile devices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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]!

You might also like