Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unity Singletons bug

Discussion in 'Editor & General Support' started by PixelFireXY, Dec 10, 2019.

  1. PixelFireXY

    PixelFireXY

    Joined:
    Nov 2, 2011
    Posts:
    56
    Hi, I just finish to learn singletons and I want to report a Unity bug that cause crash (not all the time).

    I created 3 scripts: MonoSingleton.cs, GameManager.cs and Player.cs (project package attached to this thread).

    What I did in the property of MonoSingleton.cs is instead of checking if the private field was null like this:
    Code (CSharp):
    1. public static T Instance
    2.         {
    3.             get
    4.             {
    5.                 if (_instance == null)
    6.                     Debug.Log(typeof(T).ToString() + " is NULL.");
    7.  
    8.                 return _instance;
    9.             }
    10.         }
    I checked the property itself causing a stackoverflow exception :p

    Code (CSharp):
    1. public static T Instance
    2.         {
    3.             get
    4.             {
    5.                 if (Instance == null)
    6.                     Debug.Log(typeof(T).ToString() + " is NULL.");
    7.  
    8.                 return _instance;
    9.             }
    10.         }
    When I pressed play the first time, Unity crashed.
     

    Attached Files:

  2. Pheck

    Pheck

    Joined:
    Jul 9, 2009
    Posts:
    225
  3. PixelFireXY

    PixelFireXY

    Joined:
    Nov 2, 2011
    Posts:
    56
    Sure! I will do it asap.
     
  4. vogeltanz

    vogeltanz

    Joined:
    Nov 9, 2020
    Posts:
    1
    It's not a Unity bug. A property inside the same property must not be used because an infinite cycle occurs (to get the property, you have to get the same property but to get the same property you have to get the property but to get the property ... :))
     
  5. PixelFireXY

    PixelFireXY

    Joined:
    Nov 2, 2011
    Posts:
    56
    It's not the infinite cycle the bug, but the crash of Unity if you run it. Anyway, I'm pretty sure they fixed it in later versions with an error message at the console. :)