Return to Snippet

Revision: 64279
at July 18, 2013 23:01 by Solipsist


Updated Code
using UnityEngine;
using System.Collections;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType(typeof(T));
                if (instance == null)
                {
                    Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
                }
            }
            return instance;
        }
    }
}

public class Player : Singleton<Player>{}

Revision: 64278
at July 18, 2013 23:01 by Solipsist


Initial Code
using UnityEngine;
using System.Collections;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType(typeof(T));
                if (instance == null)
                {
                    Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
                }
            }
            return instance;
        }
    }
}

public class Player : Singleton<Player>
{
}

Initial URL
http://devmag.org.za/2012/07/12/50-tips-for-working-with-unity-best-practices/

Initial Description
Singleton pattern for Unity

Initial Title
Unity Singleton

Initial Tags

                                

Initial Language
C#