Hi!
Right now i’m using DestroyImmediate to destroy duplicates of a game controller (which is a singleton) that has been set to DontDestroyOnLoad(). The reason why i need DestroyImmediate is that otherwise the Awake() and Start() functions of the duplicate scripts will run, which in my case is very time consuming. The reason for having duplicates of the game controller is that i otherwise would have to run the game from the start scene everytime just to test a certain level.
According to the reference it’s not recommended though, but is it still valid?
It is still valid and in your case i would recommend a different approach
When using a start scene, it’s better to use a simple script in each scene that checks if your singleton is there. If not it simply calls Application.LoadLevel. If your starting scene only contains the singletons, you can even do a Application.LoadLevelAdditive. It’s in general not a good idea to have duplicates of a singleton. You can also create a dedicated scene for the singleton initialization. That could even be used in the access method ( property of the singleton. So when you want to access the singleton and it isn’t there, you simply load your singleton scene additively.
hi sir i m new in unity i use destroyimmediate function my object is destroy how i come back it ?? help me please
Late answer for the people who might come across this while searching like I did:
If you don’t want to mess with your scenes or level loading code, just do something like this.
void Awake()
{
if (currentInstance)
{
Destroy(gameObject);
gameObject.SetActive(false);
return;
}
else
{
DontDestroyOnLoad(gameObject);
currentInstance = this;
}
}
Destroy
completes at the end of the current frame, but if you just disable the object and stop execution of Awake
, you can avoid some of the drawbacks without risking DestroyImmediate
. My issue was that other objects were finding the duplicate via FindObjectOfType
, so setting it to inactive worked for me.