- Home /
DontDestroyOnLoad but script being excuted multiple times
Lets say I have a scene called MainMenuScene in which I have a GameObject
, say, Datasource_GO.
On this I've assigned a script, say, Datasource_CS.cs whose contents can be simply:
void Awake() {
DontDestroyOnLoad(gameObject);
Debug.Log("Datasource_CS--Awake");
}
void Start () {
Debug.Log("Datasource_CS--Start");
}
From MainMenuScene I can go to, say, GameScene and then back to MainMenuScene.
The problem here is that with DontDestroyOnLoad I expected Datasource_GO to run the Awake method just once but everytime I load MainMenuScene, it executes Awake.
I believe it's the intended behavior so for now, I have put Datasource_GO in a dummy scene called _DummyScene that loads MainMenuScene with no route back to _DummyScene just to prevent Datasource_GO from executing multiple times.
I would like to know how you guys have/would handle this scenario or have any insight/alternatives to this.
Answer by shriya · Dec 24, 2014 at 10:37 AM
Hi staticVoidMan,
If I understood correctly, your problem is that "Datasource_GO" gameObject is multiplying every time you switch scenes as script has Dont Destroy onLoad method.. For this you can create a prefab of "Datasource_GO" with the script already assigned and instantiate in the first scene i.e your Menu with a check to see if it is already in scene or not.
if(!GameObject.Find("Datasource_GO"))
{
Instantiate (Datasource_Go);//Write correctly yourself
}
Same is to be done in your GamePlay scene, so that it does not start multiplying in gameplay scene.
I hope I am clear with my point.
Yes, that's one way but Find
is an expensive method and i generally avoid all of them.
I can however do something similar but by using references ins$$anonymous$$d.
Thanks
Your answer
![](https://koobas.hobune.stream/wayback/20220613174810im_/https://answers.unity.com/themes/thub/images/avi.jpg)