Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

[C# Tutorial] a deeper look into singletons in unity3d

Discussion in 'Community Learning & Teaching' started by paskal007r, Dec 20, 2016.

  1. paskal007r

    paskal007r

    Joined:
    Sep 6, 2013
    Posts:
    66
  2. Fabian-Haquin

    Fabian-Haquin

    Joined:
    Dec 3, 2012
    Posts:
    230
    Thanks !

    I usually do that:

    Code (CSharp):
    1. public class LazySingleton : Monobehaviour {
    2. private static LazySingleton instance;
    3.     public static LazySingleton Instance
    4.     {
    5.        get
    6.        {
    7.           if (instance  == null)
    8.           {
    9.               instance = GameObject.FindObjectOfType<LazySingleton>();
    10.           }
    11.           return instance;
    12.        }
    13.     }
    14. }
    Since I know that my class is already in the scene.
    But many of my projects are small, I see it can be a problem on a long & large dev.
    I will think about your Option B: Handcrafting next time !
     
    paskal007r likes this.
  3. paskal007r

    paskal007r

    Joined:
    Sep 6, 2013
    Posts:
    66
    Hi thanks for the reply, even if you don't use option B I'd suggest to move the FindObject there:
    https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute-ctor.html


    Code (CSharp):
    1. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    2. static void OnBeforeSceneLoadRuntimeMethod ()
    3. {
    4.           if (instance  == null)
    5.           {
    6.               instance = GameObject.FindObjectOfType<LazySingleton>();
    7.          }
    8.          return instance;
    9. }
    So that the search is not done during the game ;)
     
    Last edited: Dec 27, 2016