Hi. I have a strange problem where a script is not being destroyed even after the gameObject it is attached to is destroyed.
Relevant code below:
void Awake()
{
DontDestroyOnLoad(gameObject);
}
void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
print(GetInstanceID());
print(gameObject.GetInstanceID());
if(scene.name == "Battle"){
Invoke("setHotBar", 0.2f);
}
}
void setHotBar(){
GameObject.Find("Player").GetComponent<PlayerHotBar>().addToNextAvaliableSlot(mainHand);
GameObject.Find("Player").GetComponent<PlayerHotBar>().addToNextAvaliableSlot(offHand);
Destroy(gameObject);
print("Adding items");
}
The Object is in the menu scene. When i play the game (starts in the menu) the output is:
Instance ID: 32916
gameObject instance ID: 32912
When i progress to the new scene;
Instance ID: 32916
gameObject instance ID: 32912
Finally when i get to the ‘Battle’ scene;
Instance ID: 32916
gameObject instance ID: 32912
Adding items
This is where the object destroys itself. The object is now gone from the inspector.
Then when i go back to the map scene:
Instance ID: 32916
and when the second print statement is called, i get this;
MissingReferenceException: The object of type 'LoadoutSelection' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
LoadoutSelection.OnSceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at Assets/Scripts/KeyScripts/LoadoutSelection.cs:76)
UnityEngine.SceneManagement.SceneManager.Internal_SceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at C:/buildslave/unity/build/Runtime/Export/SceneManager/SceneManager.cs:244)
So the object is destroyed but the script is still persisting for some reason? I have no idea.
I have tried destroy(this) as well to no avail.
I’m using the EasySave plugin but not for this object or its script or anything related so i don’t see how that could interfere.
Just to clarify. I don’t want the script running at all. It should be destroyed along with the gameObject. The scripts purpose is to save the Player’s loadout selection at the menu then add it into the Player’s hotbar when the Player enters combat for the first time. Then it is destroyed.