General Performance Tips-Unity

Official Tips fromOverTheEdge

GeneralTips on Optimization

  • Profilefirst. Don't spend time trying to optimizesome obscure code or reducing the size of a texture unless you knowit is a bottleneck. Always profile your game first to find outwhere the bottlenecks are. Apple'sShark is a good tool for profiling OpenGLbased applications.
  • Profileagain. Don't forget to profile the game againafter applying your optimizations to see if they had the intendedeffect. Also this might uncover more bottlenecks.
  • Work-flow first -- performancesecond. Spend time making the creation of yourgame as smooth as possible. Being able to change and update thegame faster will also ease performance tuning later on.
  • Test the scene in the SceneView. This will tell you if the performance isbeing slowed down by the objects in the scene or scripts attachedto obejcts in the scene. If the Scene View is slugish, you mightwant to optimize the geometry or textures, if not, the bottleneckis probably in the scripting or physics.
  • Disable individual gameobjects. While in play mode, try disabling andenabling individual game objects. This can be used to narrow downwhere slowdowns are coming from.

Meshes

  • When possible, combine thenearby objects into a single object that has a singlematerial. For example, if your level containsa table with dozens of objects on it, it makes sense to combine itin your 3D application (this might require combining textures intoone big texture atlas as well). Reducing the number of objects thatUnity needs to render can boost the performance dramatically.
  • Do not have needlessmeshes. If you have a character in your game,it should probably be only 1 mesh. If you have a ship, it shouldprobably only be one mesh. There is a significant overhead for eachmesh Unity renders due to realities of hardware and drivers.
  • One material permesh. Each material that is rendered istreated like a separate mesh getting rendered.
  • The performance gained fromusing extremely low-poly meshes (like under 500 polygons) isminimal if at all there. The majority ofgraphics cards have hardware transform and lighting, which meansthey can process ridiculous amounts of polygons per second.Additionally there is overhead for submitting a mesh to thegraphics card to render, so being really thrifty on polygons isprobably only making your game look blocky.
  • Starting out, make characterswith about 1500-2000 triangles. This numbercan vary wildly, but for starting artists this should provide agood compromise between quality and performance for one level ofdetail. Note that if your model has quadrilaterals, (quads) Unitywill convert each quad into two triangles on import.

Lighting

  • Each pixel light rendered iseffectively another rendering pass. Pixellights can make your game look great but don't go too nuts withthem. However, using the Quality Manager to adjust the number ofpixel lights rendered for each quality level is a great way toprovide ample performance/quality tradeoffs in your builtgame.
  • Spot lights are more expensivethan point lights which are more expensive than directionallights. A good way to light a scene is tofirst get the effect you want correct. Then look at all the lightsyou have and see which ones are important and see if you can reducethe lights while keeping the effect similar enough.
  • Point and spot lights onlyaffect meshes within their range. If a mesh isout of range of a point or spotlight and the light is set toattenuate, the mesh will not be affected by the light thus savingperformance. This way one could theoretically have many small pointlights and still have good performance because they only affect afew objects. Remember, though, a mesh will only respond to theeight brightest lights affecting that mesh.

Textures

  • Keep the size of textures assmall as possible while still looking nice. Ifyour graphics card does not have enough memory to keep all thetextures in memory at once, they will get placed into regularsystem memory and uploaded to the card during rendering. This canbe okay as there is a lot of bandwidth available on newercomputers; however, if you go too nuts your game will completelychoke on computers with low amounts of graphics memory. There is noneed to edit the size of textures in your image editor. You canedit the size that Unity imports the image on in each image'sSettings.
  • Don't use low quality imagefiles. Trying to use jpeg files with lowquality or low-color png or gif files will not result in a smallerplayer size. Unity compresses all textures when publishing the gameautomatically, so keep the source texture files as originalhigh-resolution files. This will minimize quality degradation dueto multiple compression and decompression.

Audio

  • Use .ogg for compressedaudio. Any other audio format will be storedas uncompressed PCM audio in the published player.
  • Use uncompressed audio forsmall sound effects. Unity (as of 1.6)decompresses all ogg files on the fly. It pays to have short soundeffects played often stored as uncompressed wav or aiff files inorder not to spend CPU cycles on uncompressing the audio. Examplesof where this matters are rapid gunshots, footsteps andsimilar.

Physics

  • Each rigidbody takescomputation, so less are of courseideal. Rigidbodies also have the ability tosleep when their angular and translational velocity drop below acertain threshold. When this happens, the amount of computationthey require drops significantly and remains low until they have aforce manually applied to them or a collider touches their colliderif it exists.
  • Complicated collisions takemore computation than simpler ones. A largepile of rigidbodies with sphere colliders should be morecomplicated to process than if those spheres were laying far fromeach other on a terrain.

Shaders

  • More complicated lookingshaders probably cost performance compared to simplerones. The VertexLit Diffuse shader should bethe fastest shader that still takes a texture and responds tolighting. However, if there are no pixel lights in the scene or ifall pixel lights are off in the Quality Manager, most shaders willfall back to a more simple vertex version.

Scripting

  • Are you using the rightalgorithm? Selecting the right algorithm for atask yields much better optimization than any other code tweakingyou might do. Note that the best algorithm is not always the onewith the lowest average complexity. For small datasets, it is oftenbetter to use a slow algorithm with a small setup cost than a smartone with high initialization cost. (Eg. one would use hashtables orbinary search trees for large list of data accessed by name, but asimple list and linear search if you are only accessing a fewelements. -- although .Net's HashTable class already chooses themost optimal method depending on your data in this case.)
  • Keep your FixedUpdatefunctions as lean as possible. These functionscan get called around 50-100 times a second per applicable scriptper object, so they are a good target to optimize. If there arethings that need to be only done when the display is updated, putthat code inside the Update function.
  • If possible, disable scriptson objects when they are not needed. If youhave a large level in your game and there is an enemy kilometersaway, you can probably switch off its AI script until the cameragets closer. A good way to switch on and off objects is by usinggameObject.SetActiveRecursively(false) and sphere or box collidersset as triggers.
  • Beware the empty Updatefunctions. When creating new scripts with theAssets menu, they include an empty Update() function. Remove it ifyou don't need it as it comes at a (rather light) performance cost.This performance cost applies to all overridablefunctions in MonoBehaviour scripts, with Update and FixedUpdatebeing the main targets.
  • Refer to a GameObject by themost logical component. One couldtheoretically write:someGameObject.transform.gameObject.rigidbody.transform.gameObject.rigidbody.transform,but there is a whole lot of needless work done there. If you wantto deal with an object's Transform, refer to it in your script assuch in the first place.
  • Coroutines are yourfriends. Coroutines have only a tiny overheadand can be preferrable to an Update method that is called all thetime needlessly. For example, if you had a script to fade in andout a light on command, you could do the fading in a coroutineinstead of in Update. That way, most of the time when the light isnot fading, the script takes a minimum amount of performance. Ifthe fading was done in the Update function, you would beinefficiently polling to see if there is fading to be done.
  • Don't use methods which searchfor objects any more than is necessary. Thisincludes methods such as GameObject.FindByTag() andGameObject.GetComponent(), as well as all the component convenienceproperties (transform, light, etc.). These methods are optimised tooperate as quickly as possible, but they still have to searchthrough all the relevant objects to find the one you want. The mostimportant thing is to avoid calling search methods repeatedly inUpdate() or FixedUpdate(). Instead, call the method once, store itsresult in a member variable of your class, and then use the membervariable to access it the next time you need it.
  • Don't use SendMessage() (orsimilar functions) if you don't haveto. SendMessage() is at least 100 times slowerthan calling a function directly, and this number increases as morescripts and functions are available on the object. If you can findthe script you need ahead of time, do so and then call the functiondirectly.
  • JavaScript's (and Boo's) ducktyping takes a small amount of computation. Inperformance critical areas and when using JavaScript, try toexplicitly say what types of variables you are using when declaringthem. (Although this is often done automatically by the compilerthrough typeinference, which is just as effective as specifying the typeyourself, so your milage may vary)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值