Unity Tips - The Singleton Pattern

Hi everyone

We’ve continued our Unity series, and this time I wrote a bit on using the singleton pattern with Unity.
http://clearcutgames.net/home/?p=437

Feedback is always appreciated :slight_smile:

4 Likes

Thank you, this was a nice article! A very simple, and very useful, coding tip.

Thanks ClearCut… I was never sure about Singletons (just starting to learn C# after a few years with UnityScipt)… but your blog has made a lot more sense of it to me now. Bookmarked!

Thanks! I wrote Creating Game Manager using State Machine and Singleton pattern in Unity3d which uses singleton to persist manager, preventing its destruction when different scene is loaded.
I have used your singleton approach to store just one instance of an object.

Here is the code I used in the post:

public class Singletone {
protected Singletone() {}
private static Singletone _instance = null;

public static Singletone Instance { get {
return Singletone._instance == null ?
new Singletone() : Singletone._instance;
} }
}

public class GameManager 
{

    private static GameManager instance = null;
    

    public static GameManager GetInstance()
    {
        if(instance == null)
        {
            instance = new GameManager();
        }
        
        return instance;
    }
}

The MathFul game sounds interesting,where can we download it,and can you share the source code with us?:slight_smile:

Thanks, I keep reading this method mentioned but could never find a guide!

Thanks for this article, it will probably help me for my current project. (:

As a feedback, I would say that your last two images are corrupted or something else, so they’re not displayed anymore !

You must use some sort of locking between your if(instance == null) and your instatiation since it might happen that you passed the nullity check and another thread will create new instace at the same point cause he passed the nullity check as well - than your thread and the other thread continues and both create new instance - 2 instances is not a singleton

The right way to go in your path is :
Check nullity > lock the thread > check nullity again > create new instance > release lock and return.

Thanks a lot! With this I have solved a tone of bugs…

This was really helpfull :slight_smile:

I know this is an ooold post, but the last two images on the blog are broken (and I didnt want to use the facebook posting system on the blog).