[FIXED] Destroy(myObject) seems to be working but my Hierarchy is still filling up with objects

In my first scene I have an object NumberCruncher that has an attached script called NumberCruncher.cs It is set not to destroy itself when a new scene loads.

In my second scene I have an object LostCanvas that has an an attached script Menu_Lost.cs which takes some values from NumberCruncher and then destroys NumberCruncher.

Findings …
NumberCruncher does survive the loading of the second scene and Menu_Lost.cs can pull some values correctly from it. If I ask Menu_Lost to destroy NumberCruncher, NumberCrunchers values are reset when I reload my first scene. Correct! If I do NOT ask Menu_Lost to destroy NumberCruncher, NumberCrunchers values remain when when I reload my first scene. Correct!

While it all functions correctly my Unity Hierarchy does not show the old NumberCruncher beening removed properly when Menu-Last asks.

example

Scene One (Level 1)
NumberCruncher has values set to 0 Correct!

load scene two …

Scene Two (Lose Screen)
NumberCruncher has various values set correctly that Menu _Lost can access Correct!

load scene one …

Scene One (Level 1)
NumberCruncher has various values set to 0 Correct! Correct! (see pic 1)
(additional old) NumberCruncher This looks like the NumberCruncher game object without an attached NumberCruncher.cs. Wrong! (see pic 2)

So I think that I am not getting the correct reference to destroy the NumberCruncher object properly

First scene

NumberCruncher.cs attached to the NumberCruncher object

public class NumberCruncher : MonoBehaviour {

void Awake() {


      
            GameObject.DontDestroyOnLoad(gameObject);
}

}

Second scene
Menu_Lose.cs attached to the LostCanvas object

public class Menu_Lost : MonoBehaviour {

    /* -----< DECLARATIONS >----- */
    //INSPECTOR
    public NumberCruncher nc;
    /* -----< DECLARATIONS -END >----- */


    void Start () {

        //Find the running NumberCruncher
        nc = FindObjectOfType<NumberCruncher>();

       //Do some stuff .....

        Destroy(nc);    //Finished getting data from Number Cruncher. Destroy it!
    }
}

pic1

pic2

Thanks for looking

Paul

Nc is a reference to a component. You are destroying the component attached to the gameobject not the gameobject itself

That’s what I thought. How do i destroy the Object then?

Try
Destroy(nc.gameObject);

1 Like

Perfect!

Many thanks :slight_smile: