Question by
saintmaykel · Oct 15, 2016 at 04:34 PM ·
gameobjectdestroyloadleveldontdestroyonloadload scene
How can I destroy a GameObject after a scene is loaded?
Hi, I'm having a hard time with this issue, currently I have Timer as the top layer inside it is the text and the image for my timer. i use dontDestroyOnLoad for my timer to pass through some scenes that needed a timer, but when I loaded the main menu the timer is still there. how can i destroy a GameObject that has dontDestroyOnLoad attached to it?
Comment
Best Answer
Answer by villevli · Oct 15, 2016 at 05:50 PM
Add this to the script in the Timer gameobject:
void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// here you can use scene.buildIndex or scene.name to check which scene was loaded
if (scene.name == "MainMenu"){
// Destroy the gameobject this script is attached to
Destroy(gameObject);
}
}
$$anonymous$$an! you saved my day! without you I don't know what to do! THAN$$anonymous$$ YOU SO $$anonymous$$UCH!
How about if I have many scenes to destroy a object that its on DontDestroyOnLoad? Correct me if I'm wrong.
if (scene.name == "$$anonymous$$ain$$anonymous$$enu"){
// Destroy the gameobject this script is attached to
Destroy(gameObject);
} else if (scene.name == "$$anonymous$$ain$$anonymous$$enu2"){
// Destroy the gameobject this script is attached to
Destroy(gameObject);
}
Thank you so much been looking for a solution on this for ages :)