The Pros with Singleton and Scalability

 The Pros with Singleton and Scalability

Pedro Colon


A Different Kind of Blog

This blog is going to be a little different. Rather than talking about a problem, we are going to talk about the pros of a good foundation can give us when adding in new tasks within the project. And that good foundation is our singleton for the Audio Manager. But first what is a singleton?

To be quick, a singleton uses a public static instance to allow it to be called by other scripts without having to get a reference. I will say, this is not the go to pattern to use (granted no pattern is the go to but singleton can easily make things go haywire fast), but singleton works really for objects you don't want to be destroyed and carry over between scenes. One thing I have used it for is the Audio Manager. While I could just place a new Audio Manager between every scene, I found it would be redundant and more than likely another object needed to load and would just waste time with the engine to always load a new audio manager. So using the singleton method along with making sure it isn't destroyed (unless it needs to be) makes it worth using (or at least trying).

What is the benefits to this? To put it simply, this benefits us by allowing us to simply have code that will change whatever sounds that has to be change. For example, music! With the singleton, we are able to change the music based on what kind of level it is and play the audio accordingly. And since the music is 2D rather than 3D in terms of sound-depth, it makes things a bit easier to juggle. What also makes it easier to juggle is being able to change the music pitch when a certain count is met. Granted, I do need to make a change within the code to better check it with an event rather than update, but the fact that is working shows that it can be done.

This is mainly a lot of words and that's mainly because it is a bit hard to fully demonstrate. At this point a full-on video take would possibly serve better but I have been this post on hold long enough and there is other things I must do before this milestone submission.

One word of advice, don't use singleton everything, it can quickly make the code clutter. Make sure it is used as it needs be and objects that are important but not in the minute to minute gameplay (player control script for example should not be singleton).

Comments

Popular posts from this blog

The Pitfalls of Crafting a Position Placement and Lap Counter for Kart Racing Games

Troubleshooting Unity GameManager Input Handling

Only one line of code