- Home /
DontDestroyOnLoad duplication
Hi,
I know there are countless threads about this problem but I couldn't find one that addresses my specific problem.
So basically I have my UI elements which I want to carry through all my scenes until I go back to the very first scene (where the usual duplication happens). Then I have the situation, that I would like to reset all my UI elements to the default state. That actually happens if I don't do anything due to the duplication which is then located above the original UI elements in the hierarchy and is displayed instead of the original UI.
But since I can imagine that it is not quite the best idea (regarding performance) to keep all the duplicates in the scene I need a way to delete the original version and only keep the duplicate when loading the original scene.
I tried the following code which works nicely to destroy the duplicate but keeps the original.
using UnityEngine;
public class DontDestroy : MonoBehaviour
{
private void Awake()
{
int destroyableObjects = FindObjectsOfType<DontDestroy>().Length;
if (destroyableObjects != 1)
{
Destroy(this.gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
}
is there a way to keep the duplicate and destroy the original?
Thanks in advance :)
Answer by Hellium · Dec 12, 2018 at 12:52 PM
using UnityEngine;
public class DontDestroy : MonoBehaviour
{
private static DontDestroy original;
private void Awake()
{
if (original != this )
{
if( original != null )
Destroy(original.gameObject);
DontDestroyOnLoad(gameObject);
original = this;
}
}
}
Thanks. I see the idea behind the script and in my opinion it actually should work like that but sadly it doesn't seem to do anything.
Duplicates still get created and none of the objects get destroyed...
Thanks a lot! Works like a charm!
you might want to edit in the curly brackets for the last if statement to prevent confusion for other users :)
Thanks again!