The singleton pattern is structurally a very simple pattern, as it only spans a single class. To create a singleton you have to pay attention to two aspects: the class should have global access and there should be no more than one at a time. As all the tasks are quite short you will have to come up with three different singleton implementations. It is recommended to do them in order, as they are intended to have a ascending difficulty curve.
Part 1
Create a classical singleton implementation, which does not extend any other class.
- The singleton should have a static Instance property or a GetInstance method to provide global access.
- The singleton should have a private constructor, so it could only be constructed from inside the class itself.
- The singleton should be initialized lazily - it is created when it is accessed for the first time.
Part 2
Create a singleton component extending the Monobehaviour.
- In this case due to the entity-component system, the constructor can not be made private. Use the Start method to control the number of instances.
- Unity destroys all components during scene change. Call the relevant method to make sure this does not happen.
Part 3
Create a generic singleton component. When extending this class, the child class:
- Is equivalent to task 2 implementation, but singleton behavior can be accessed by defining the class as Child : Singleton.
Part 4
Answer the following questions as a submission comment:
- In the component pattern, all components must have a public constructor due to the Instantiate method. Since the constructor is public, more than a single object can be constructed. Since the goal is to still have only a single singleton component at a time, then any additional instances of it should be destroyed immediately after they are created. In this case should only the component be destroyed or the gameobject this component was attached to. Why?
- Think of a feature or system in a game, which could be created as a singleton. Are there any downsides to using singleton in this case? What other approach could you take to avoid these downsides?