Posted By


Solipsist on 07/18/13

Tagged


Statistics


Viewed 548 times
Favorited by 0 user(s)

Unity Singleton


/ Published in: C#
Save to your folder(s)

Singleton pattern for Unity


Copy this code and paste it in your HTML
  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>{}

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.