How to destroy a gameobject by GameObject.Find

I’m using a script that plays audio Through multiple scenes and when i get to the “Game” scene i want the object to destroy itself… I don’t know how to acomplish this… But i thought it would be something like this.

Make a new script… Place it into a blank gameobject in the Game Scene…

using UnityEngine;
using System.Collections;

public class StopMusicOnGameScene : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update ()
	{
		GameObject.Find("AudioThroughScene");
		Destroy (gameObject);
		Destroy(this);
	}
}

But as you can see this wont work because its deleteing the gameobject itself before it deletes the AudioThroughScene Object… How can i acomplish this?

I’m new to Scripting Sorry.

Hi,

You’re currently destroying “this” component. This, however, means the script that it’s run through.

try this:

using UnityEngine;
using System.Collections;
 
public class StopMusicOnGameScene : MonoBehaviour {

    public GameObject AudioObject;
    
    // Use this for initialization
    void Start () {
        AudioObject = GameObject.Find("AudioThroughScene");
    }
 
    // Update is called once per frame
    void Update ()
    {
       Destroy(AudioObject);
    }
}

I don’t know your code but this should do, for now. And you should realy try to never do a GameObject.Find in the Update.
GameObject.Find is a pretty heavy call.