Posted By

Solipsist on 07/18/13


Tagged

Unity


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfinrud55


Unity Singleton


 / Published in: C#
 

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

Singleton pattern for Unity

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  5. {
  6. protected static T instance;
  7.  
  8. public static T Instance
  9. {
  10. get
  11. {
  12. if (instance == null)
  13. {
  14. instance = (T)FindObjectOfType(typeof(T));
  15. if (instance == null)
  16. {
  17. Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
  18. }
  19. }
  20. return instance;
  21. }
  22. }
  23. }
  24.  
  25. public class Player : Singleton<Player>{}

Report this snippet  

You need to login to post a comment.