Unity is a fabulous tool for not only games but also interactive entertainment, simulations, etc. And there are many good tutorials on tips and tricks to optimize performance and code readability. I compiled this list as a memo to myself when starting out on Unity, so I can always refer back to the basics and hoping that this can help someone else too.
- Object pooling. Object pooling is a pretty cool trick and it improves performance because you can reduce the number of Initiate() and Destroy() calls. To illustrate why Destroy can be bad, I attached a screenshot of a project I was building with Unity. I'm not going to go into the details of Object Pooling because there are already many good tutorials out there. One of them being this one. One thing to always keep in mind is that it is easy to get MissingReferenceException if you accidentally Destroy() the pooled objects. It happened to me once where I attached one script to multiple prefabs which behave the same except that some are Instantiated and some are Pooled.
- Caching Lookup Objects. Do not do GameObject.Find too often. Do it once and store it in a private variable and reuse that variable.
- Do not use too much iTween. Go with your own manual implementation with Update().
- Avoid Vector3.Distance or Vector3.Magnitude. To find the distance use sqrMagnitude instead.
- Be consistent with the structure of prefabs. Consider the following scenario. You have a Particle system attached to an object. You decide to cache the lookup so you do the following.
And then, when you want to start the particle system, you call it from some method as follows.ParticleSystem myParticles; void Start(){ myParticles = myObject.GetComponent<ParticleSystem>(); }
This will not raise an error during runtime but the particle system will not be found and the desired special effects will not be displayed. Actually this is more of a human error issue and not directly related to Unity but the error reporting (or lack thereof) in Unity can cost development time.void LaunchParticleSystem(){ myParticleSystem.GetComponent<ParticleSystem>(); }
- When calling a method with parameters, pass by reference instead of making it return an object. This is one of the most effective cost reduction in a game I was making. I had many coroutines routinely updating a List<> of Vector3 positions. After modifying the method to be passed with ref, the performance improved significantly.
Comments
Post a Comment