1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
static GUIManager myInstance;
public static GUIManager Instance
{
    get
    {
        if (myInstance == null)
            myInstance = FindObjectOfType(typeof(GUIManager)) as GUIManager;

        return myInstance;
    }
}
1
2
3
4
5
6
7
static GUIManager myInstance;
public static GUIManager Instance { get { return myInstance; } }

void Awake()
{
    myInstance = this;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
   protected static T instance;
 
   /**
      Returns the instance of this singleton.
   */
   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;
      }
   }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public abstract class Singleton<T> : MonoBehaviour where T : Component
{
  [SerializeField] private bool isPersistant;

  protected static T Instance { get; private set; }

  public virtual void Awake()
  {
    if (isPersistant)
    {
      if (Instance == null)
      {
        Instance = this as T;
        
        DontDestroyOnLoad(this);
      }
      else
      {
        Destroy(gameObject);
      }
    }
    else
    {
      Instance = this as T;
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Test
{
    private static readonly Test instance = new Test();
    private Test() { }
    public static Test Instance
    {
        get
        {
            return instance;
        }
    }
}