- Home /
Question by
Poseidon1145 · Sep 30, 2017 at 12:50 AM ·
c#gameobjectdestroy
Destroy specific gameobject with name
hello I need to destroy an object by its name in the scene since I need to destroy many objects and to do it by tag would be very long
if(oakTreeHealth <= 0) {
Destroy(gameObject.Find("Oak Tree 2"));
}
but it does not work
Comment
Best Answer
Answer by YoucefB · Sep 30, 2017 at 12:31 PM
You have to check if the Object exist or not then if yes destroy it, or it will raise a NullReferenceException
string name = "Oak Tree 2";
if (oakTreeHealth <= 0){
GameObject go = GameObject.Find (name);
//if the tree exist then destroy it
if (go){
Destroy (go.gameObject);
Debug.Log(name + "has been destroyed.")}
}
}
Exemple To destroy multiple objects
// list of object names that you want to destroy
string[] myObjectsNames = new string[]{"Oak Tree 1","Oak Tree 2"};
if (oakTreeHealth <= 0){
foreach (string name in myObjectsNames) {
GameObject go = GameObject.Find (name);
//if the tree exist then destroy it
if (go)
Destroy (go.gameObject);
}
}
Answer by AshwinTheGammer · Sep 30, 2017 at 01:58 AM
try this
public GameObject Oak Tree 2;
if(oakTreeHealth <= 0) {
Destroy(GameObject.Find("Oak Tree 2"));
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612135942im_/https://answers.unity.com/themes/thub/images/avi.jpg)