November 5, 2013 by Nikos
Like many other developers/studios/companies etc, I too have started experimenting with Unity. Let’s just say it follows a different logic from anything I’ve used so far. I have to get accustomed to it and it’s gonna be a lot of work. What troubles me is that I might want to code some actions that are project wise or even scene wise and there is no global script. I have to resort to “hacks” , for the lack of a better word, to accomplish them. Like using the Start function to encapsule my code so that it starts immediately when Play is issued and then using it as a component on the Camera for example so that the script itself will be used and will run at some point (just including scripts in a project doesn’t mean they are in use when it runs).
Another example would be the use of Singletons as managers. I watched this great presentation by Timothy Cooper of Unity Development Team about some hints and tips that would make development easier, faster and better in quality. He talked about not using the Find functions because they traverse the whole scene and they introduce major overhead when you might want to do something fairly simple. It’s true, it is very wasteful in terms of performance. When you want to call a method for a specific object in the scene you have to go through every object in the scene to get to it. If there were only a few objects in the scene the overhead would not be that bad but that is usually not the deal.
So Tim Cooper proposed the use of Singletons. Classes that have only one instance in the whole application and are static so that they can be called wherever and hold a list of objects of a certain type. When you need a wall you will call the WallManager, when you need an enemy the EnemyManager etc. Singleton classes have a reference to a Singleton object inside the class which is the instance pointer everyone calls in order to access the list. This pointer has to get initialised at some point. In C++ you’d get all Singletons initialised in some Init function at the start of the application before running anything else (usually they were called while an intro was shown on screen). In Tim’s implementation that initialisation happens OnEnable. After using the Manager implementation in a test scene I found I couldn’t use the Manager without attaching it to some object on scene. The object I thought was best suited was a new empty and abstact game object whose express purpose would be to hold all scene-wise scripts. The truth is that I just found that out while writing it but it only goes to show how much different the logic behind this game engine is with standard programming and how much exercise I have in front of me in order to get accustomed to it.