Singleton Pattern
  • Ensures that the class has a single instance.
  • Access to the class is simple and requires no references.
This pattern is the subject of much discussion since it violates the SOLID Single Responsibility Principle by introducing global state and because the class is now in charge of two tasks.
 

Implementation

First, a private static instance of the class must be created and initialized in the Awake method.


 
Additionally, we want to prevent destroying the game object when the scene reloads. A parent Game Object is required for a component that utilizes the Do Not Destroy On Load property.
 

 
The public Get Instance method must now be added.
 

We must now create the class. Play the background music's audio clip.
 

 
Now, all I have to do is tell the Singleton to play the clip from whatever script I want to play ambient music from.


 
Now, one of the music options is played when I launch the game. The scene reloads if I hit the R key, and there is now just one Ambient Player present. Take note of the warning I receive each time the scene reloads informing me that an ambient player is already present in the scene.
 

 

Conclusion

A Few Issues Are Solved by the Singleton Pattern.
  • Ensures that the class has a single instance.
  • Access to the class is simple and requires no references.
You needlessly make it a permanent Game Object in order to use it in Unity. Persistent Game Object Spawner is one of the better methods for adding persistent game objects to your game.

Prior to utilizing it, you must set it up in at least one Scene, which causes certain issues with Unity (you can introduce bugs, break SOLID principles, and add global state to your game). I personally try to steer clear of this trend.
 
Category: Unity | Added by: Viktor_Surzhko (2021-06-01)
Views: 1430 | Rating: 0.0/0
Total comments: 0
avatar