Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Singleton Event

Discussion in 'Scripting' started by Marble, Sep 28, 2006.

  1. Marble

    Marble

    Joined:
    Aug 29, 2005
    Posts:
    1,271
    I have a trigger that causes an event that's only supposed to happen once, when the level first loads. I never want it to happen again. When I tell it not to destroy when another level loads and then disable it, Unity makes a copy of the gameObject next time I load the first level and the event happens again. How can I keep this from happening?
     
  2. Talzor

    Talzor

    Joined:
    May 30, 2006
    Posts:
    197
    Whenever a scene is loaded unity makes an instance of all objects in a scene, so if a scene has an object marked as "don't destroy on load" and the scene is loaded multible times, you get multible copies of the object. To avoid this you can do the following (c#):

    Code (csharp):
    1.  
    2. public class MySingleton {
    3.    private static MySingleton instance;
    4.    
    5.    void Awake() {
    6.       if (instance != null  instance != this) //IF we already has an instance of this class
    7.          Destroy(gameObject);
    8.       else {
    9.          instance = this;
    10.          DontDestroyOnLoad(this);
    11.       }
    12.    }
    13. }
    14.  
     
  3. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    Another way is to put all global manager objects into Scene 0 and nothing else into that scene. Once scene 0 is loaded immediatly load the first actual scene and never reload scene 0.
     
  4. Marble

    Marble

    Joined:
    Aug 29, 2005
    Posts:
    1,271
    Works nicely. Thanks!