Thursday, 9 October 2014

2 Simple rules to improve performance in Unity 3d when writing Scripts

So you created beautiful looking game that run 90 fps on your machine and then your exported it to mobile device and your excitement disappeared once you opened it -slow, lag, unplayable. If you haven't experienced that either you are genius talented video game designer or your game is not very resource demanding. I have been in this situation and my solution was to carefully start optimizing game so it will run much smoother and users that still have few years old devices(like me) can enjoy the game. This is not holy grail unity tutorial, but it definitely helps me in many occasions.

It is very important to think about performance in an early stage when creating video game/app using unity game engine. Some bad design can cause headache in the future, especially when your game gets bigger and more resource demanding.

Of course writing optimised script is not the only way to improve performance in unity games. Another way is to reuse materials, avoid using transparent shader on mobile devices etc.

Due to my experience I found out that those 2 very simple tricks works well.

1. Cache an object when using it often (especially in Update function).


Example.

   void Start ()

   {

       double totalA = 0;

       double totalB = 0;

       int counter = 1000000;

       // Caching our transform

       Transform tr = GetComponent();

       var currentTime = DateTime.Now;

       // First test with cache

       for (int i = 0; i < counter;i++)

       {

           Vector3 vec = tr.position;

           vec.x = 10;

           tr.position = vec;

       }

       totalA = (DateTime.Now - currentTime).TotalMilliseconds;

       // Second test with no cache

       currentTime = DateTime.Now;

       for (int k = 0; k < counter; k++)

       {

           Vector3 vec = transform.position;

           vec.x = 10;

           transform.position = vec;

       }  

       totalB = (DateTime.Now - currentTime).TotalMilliseconds;

       print (totalA);

       print (totalB);

   }

1st loop will perform faster.

2. Use static variables rather than public.


 Static variable belongs to an class rather than object, therefore it is faster to access. Careful as if the same class is being used for the same prefabs(eg enemy), if you kill one enemy, all of them will be dead.  If that approach at least helped you to get extra fps let me know!