Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How can I delete the gameobject the script is in (c#)

Discussion in 'Scripting' started by supergaming3778, Jun 26, 2022.

  1. supergaming3778

    supergaming3778

    Joined:
    Jun 26, 2022
    Posts:
    2
    Code (CSharp):
    1. How can I delete the gameobject the script is in (c#)
    2. using UnityEngine;
    3. public class EnemyCollision : MonoBehaviour
    4. {
    5.      void OnCollisionEnter(UnityEngine.Collision collisionInfo)
    6.      {
    7.          if (collisionInfo.gameObject.tag == "Dart")
    8.          {
    9.              ?
    10.          }
    11.      }
    12. }

    I want to put a script at the question mark that deletes any object that uses this script if the if statement is true.
     
  2. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,135
  3. supergaming3778

    supergaming3778

    Joined:
    Jun 26, 2022
    Posts:
    2
    so do i need to make the gameobjects name a variable and put it in the Destroy () thing?
     
  4. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,135
    You can retrieve the GameObject that the current component is attached to via the gameObject property.

    A GameObject can be destroyed by passing it to the Destroy method as an argument.

    So
    Destroy(gameObject);
     
  5. bplc

    bplc

    Joined:
    Mar 10, 2022
    Posts:
    104
    supergaming3778
    public GameObject myGameObject;
    Destroy(myGameObject);


    here you will destroy the game object, which you will have dropped, in your myGameObject variable from the inspector.



    If you write :
     Destroy(gameObject);

    This means that you destroy the GameObject to which the script is attached.
    (It's all about capitalization ^^)