Hi, need help in referencing objects in the inspector.
I have 2 scenes I,e main_menu and level. At scene main_menu there are a couple of game objects that are dontdestroyonload. on those objects sound effects and game music and scripts are attached. When I select the level from the main menu it works fine till now I can play game without any error or issue which is scene 2 l(named level 3). when I go back to scene 1 that is the main menu references in the inspector to the objects under objects remove or null it says missing object but object is present under dontdestroyonload . As in image 2.
I guess that this is why… It was like this for me at least, before I fixed it.
When you go back to another scene working the first time, the do-not-destroy object may/will be created again. And if you don’t want that you must also make the objects Awake() function to “fix” this by destroy the new object (not the old one from before, or you will invalidate the references you hold).
This is how it can be done
public static GameManager theGM = null;
//first code to run
void Awake()
{
//singleton
if (theGM == null)
{
theGM = this;
}
else if (theGM != this)
{
//enforce singleton pattern, meaning there can only ever be one instance of a GameManager.
Destroy(gameObject); //<- Be careful, this makes OnDestroy() be called and we don't
// want to deinit everything there (for example if you have external things setup the
// first time that you want to keep function)
return;
}
//the rest is done once only...
DontDestroyOnLoad(gameObject);
//...
}
//example:
//cannot do this, because it is called when Awake is called a 2nd time when loading another scene!
// so OnDestroy() gets called for the new object that is then destroyed to enforce singleton
//we only want to do this when the app exits
/*private void OnDestroy()
{
if (!bSteamAPIInited)
return;
SteamAPI.Shutdown();
}*/
If this doesn’t help you, share the relevant code, so we can look at it.