Home > Software engineering >  How to Destroy a Parented Object in Unity
How to Destroy a Parented Object in Unity

Time:02-02

I am making a shooting game in Unity, and the enemy looks close to a human because I have added many different shapes to make up an enemy. The problem is, when I shoot the enemy, the different shapes disappear instead of the whole enemy. Here is my collision code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponCollision : MonoBehaviour
{
    void OnParticleCollision(GameObject other) 
    {
        Destroy(other);
    }
}

Is there a way to delete the whole object instead of all the different parts? Thanks!

CodePudding user response:

You can try GameObject.transform.parent to get the parent object of the current transform. You can read at Transform.parent

Do something like this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponCollision : MonoBehaviour
{
    void OnParticleCollision(GameObject other) 
    {
        Destroy(other.transform.parent);
    }
}

CodePudding user response:

You can destroy a parented object in Unity using the Destroy method from the UnityEngine.Object class. Here's how you can use it: using UnityEngine;

public class Example{ public GameObject parentObject;

private void DestroyParentObject()
{
    // Destroys the parent object and all its children
    Destroy(parentObject);
}

}

In this example, the Destroy method destroys the parentObject and all of its children. The Destroy method takes an object reference as its argument, which can be a reference to a GameObject, a Component, or any other UnityEngine.Object.

You can also specify a delay time in seconds before the object is destroyed, by passing a second argument to the Destroy method:

Destroy(parentObject, 5.0f);

In this example, the parentObject will be destroyed after 5 seconds.

  • Related