Destroy
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 67 of 85.
Destroy(obj) removes a GameObject from the scene, children included. A second argument delays it: Destroy(obj, 2f) removes it 2 seconds from now, and the script that called it carries on at once. This cannon fires on Space, and each bullet it makes is gone 2 seconds later:
public GameObject bulletPrefab;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
Destroy(bullet, 2f);
}
}Pass the copy, not the prefab: Destroy(bulletPrefab) is refused with Destroying assets is not permitted to avoid data loss. And pass a GameObject when you mean the object. Inside a script, gameObject is the object the script is on, so Destroy(gameObject) removes that object, while Destroy(this) removes only the script and leaves the object standing.
Destroy never happens on the spot. Unity removes the object at the end of the current frame, after the frame's Update() and LateUpdate() calls, so the lines after Destroy still run and the object can still be found until the frame is over.
Challenge
MediumClear the old coins away, and let Space remove the chute.
- Keep the new coin,
GameObject coin = Instantiate(...);, then callDestroy(coin, 3f);. - On
Input.GetKeyDown(KeyCode.Space), callDestroy(gameObject);.Destroy(this)would remove only the script.
Press Play: each coin vanishes after 3 seconds, and Space stops new ones. Then Check.
Try it yourself
using UnityEngine;
public class CoinChute : MonoBehaviour
{
public GameObject coinPrefab;
public float interval = 1f;
float timer;
void Update()
{
timer += Time.deltaTime;
if (timer >= interval)
{
Instantiate(coinPrefab, transform.position, Quaternion.identity);
timer -= interval;
}
// Space: destroy the chute
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground