- Home /
DontDestroyOnLoad Not Working At All
I have quite a few objects which I'd like to keep for the next three scenes (about 25 objects total). I made the script below, and attached it to all the objects. Unfortunately, the objects destroy when I test the game and make it to the next level. There are no script errors, and I can't see anything wrong with the scene I've set up. Basically, the script does nothing and I'm not sure why. If anyone knows common problems with DontDestroyOnLoad, or anything else that might help, it would be much appreciated.
#pragma strict
function Start () {
DontDestroyOnLoad (transform.gameObject);
}
When do you actually change the scene? As @iamsidv states, check if Start is at all called. If it's not, that may be caused by Application.LoadLevel being called before e.g. Awake
The scene changes aprox. 2 $$anonymous$$uets in. How would I tell if the start function is being called?
Answer by andsee · Sep 02, 2015 at 12:48 PM
One other thing to check is that these objects are in the root of the hierarchy. If not their parent object may get destroyed which unfortunately means their demise too.
Well I knew I wasn't very bright, but this was a really stupid mistake. Yeah, I had them grouped under something that got destroyed. Thanks.
Wooooooooooooowwwww..... Tried to do a little hierarchical cleanup the other day and stuck my game manager objects (that's supposed to persist between scenes) under an empty with w few other items.... Good God, was $$anonymous$$ring my hear out. Debug logs everywhere. Thank you sir. You are a gentleman and a scholar.
Answer by pmaloo · Sep 02, 2015 at 12:00 PM
Put it in Awake
.
If you put it in start, that object can be destroyed before start is called by actions in Awake/OnEnable
I originally did have it as Awake, but that wasn't working so I changed it to Start.
@SpartanSperos Check the answer by @andsee. Its a very common mistake to make the DoNotDestroyOnLoad a child of perishable parent.
Also make sure that you are not specifically destroying the object from another script.
Answer by unity_VYAo9PCTYYamFA · Jun 11, 2021 at 07:58 PM
Put it in First line of Awake function it will solve. because it need to execute first,Put it in awake