- Home /
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.
Answer by Shgoedt · Jun 03, 2013 at 09:26 AM
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.
@Shgoedt that was great. Helped me remove a DontdestroyOnLoad script that i only wanted to go through to 1 other scene and not the others. I would of replied under your post but i didnt have permissions apparently!?
Your answer
 
 
             Follow this Question
Related Questions
fmod 3d listener only updates once at start of script 0 Answers
Calling sound once in update 1 Answer
c# and game objects active state issues 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                