Write a simple Unity script that destroys the gameobject after a specified amount of…
- User
Write a simple Unity script that destroys the gameobject after a specified amount of seconds
- Assistant
Certainly! Below is a simple Unity C# script that destroys a GameObject after a specified amount of seconds. You can attach this script to any GameObject in your scene.
using UnityEngine; public class DestroyAfterSeconds : MonoBehaviour { // The time in seconds after which the GameObject will be destroyed public float secondsToDestroy = 5f; // Start is called before the first frame update void Start() { // Call the Destroy function after the specified time Destroy(gameObject, secondsToDestroy); } }How to Use the Script
-
Create a new script: In the Unity Editor, right-click in the Project window, select
Create > C# Script, and name itDestroyAfterSeconds. -
Copy the Code: Open the newly created script and replace the default code with the code above.
-
Attach the Script: Drag and drop the script onto any GameObject in your scene (like a Cube, Sphere, etc.) in the Hierarchy view.
-