Destroy a GameObject in Unity 3D C#

Hello programmers, In this article, I will show how to destroy a GameObject in Unity 3D with C# programming.

If you are a beginner and want to create your own game but don’t know how to destroy the GameObject don’t worry it is pretty simple.

Before we get started with the building process, we need to know a few concepts. Let’s first discuss them.

Object.Destroy

Destroy function is used to remove or destroy the GameObject or components from the scene. This can also be done by time delay, by using a second argument, a float number.

Syntax:

public static void Destroy(gameObject,t);

gameObject = The object to be removed or destroyed.

t = time delay for destroying an object.

 

Now let’s get down to the program part, here is an example of destroying a GameObject in Unity with the help of C# programming.

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

public class DestroyObject : MonoBehaviour
{
    public GameObject sphere;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    void OnCollisionEnter(Collision otherobj)
    {
        if (otherobj.tag == "player")
        {
            Destroy(sphere, 10f);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

In the above code, we are checking the collision with an object of a specific tag. If it matches, then our object will be destroyed. That’s the way to destroy our GameObject in Unity 3d by writing C# code.

Also, read: Change the material color of an Object in Unity 3D C#

Leave a Reply

Your email address will not be published.