Search Unity

Help with accidental destroy, even when using DontDestroyOnLoad

Discussion in 'Scripting' started by awillshire, Jan 27, 2015.

  1. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    Hi All,

    I have a class that is designed to be a singleton, and is using DontDestroyOnLoad on the game object created during instantiation.

    I am finding that during some scene changes the game object is in fact destroyed (I have a debug message in the class OnDestroy method). I've traced it to the moment when the scene transition takes place, but I can't work out why it happens when I have already configured it with DontDestroyOnLoad. The game object creation logic is below.

    Hoping to receive any advice, especially if anybody is aware of how the DontDestroy can be overridden. Something is knocking it out somewhere!

    Kind Regards,
    Andrew.

    Code (CSharp):
    1. if (_instance == null) {
    2.     GameObject singleton = new GameObject();
    3.     _instance = singleton.AddComponent<T>();
    4.     singleton.name = "(singleton) " + typeof(T).ToString();
    5.  
    6.     DontDestroyOnLoad(singleton);
    7. }
     
  2. gamer_boy_81

    gamer_boy_81

    Joined:
    Jun 13, 2014
    Posts:
    169
    Interesting !

    Can you post more of the codes/scripts associated with this ?

    Here are some things to try out/ think about :

    - Is it possible there is a duplicate which doesn't have DontDestroyOnLoad and it is that one which is destroyed
    and not your singleton ?

    - Make an empty scene with just this script and transition to an empty scene and see if it still happens.

    - Is the destruction happening in the current scene or the scene you transition to ?

    - you said that it happens during "some scene changes"..what could be different between the problem
    and the non-problem scene transitions ?

    Looks like the answer to this problem is a simple one..but its difficult to figure out
    w/o much info.
     
    awillshire likes this.
  3. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    Hi!

    Thanks so much for the prompt response! I took your advice and played around a little with the scenes, plus rebooted, and I'll be darned if the problem didn't sort itself out. I'm not even 100% sure how it was fixed, but it's certainly working a treat!

    Thanks for the help,
    Andrew.