Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- 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)
- {
- //Try finding non-active scene object
- var objects = Resources.FindObjectsOfTypeAll<T>();
- if(objects.Length > 0)
- instance = objects[0];
- }
- if(instance == null)
- {
- Debug.LogError("An instance of " + typeof(T) +
- " is needed in the scene, but there is none.");
- }
- }
- return instance;
- }
- }
- }
- // Example
- public class GameManager : Singleton<GameManager>
- {
- public int value = 1;
- }
- // you can access value from anywhere with this
- GameManager.instance.value;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement