How do I create an object that should essentially be destroyed a few frames later?
What I want to do is cast a line from an object to the player, and if it hits something else, create an object that exists one frame, set a few settings (e.g. an audio source), and then delete it again. Think of a sound that plays when hitting an obstacle with the line.
I managed to get everything working up until the deletion of the object. What I currently do is:
Instantiate a new GameObject
Set a few things on this GameObject (e.g. add an audio source)
Start a coroutine on this GameObject that destroys it after a second
Is this the optimal way of doing this?
Ideally, I’d want to create a lot of gameobjects. Like, create a scattering laser effect, with bounces against walls, that is active every frame. Is this possible in Unity? And what is the best way to do this with a script?
This is just something that I’m trying to create. In the end, I would try to devise a better way. You know what they say about premature optimization…
Object pooling is more efficient, especially if you plan to create a lot of these game objects. Github has a few repositories with object pooling examples.
using UnityEngine;
using System.Collections;
public class DestroySelfTimed : MonoBehaviour
{
public float lifeTime = 0.01f; //How many seconds(or fraction thereof) this object will survive
private bool timeToDie = false; //The object's trigger of its inevitable DEATH!!!
void Update ()
{
lifeTime -= Time.deltaTime;
if (lifeTime <= 0.0f)
{
timeToDie = true;
}
if (timeToDie == true)
{
Destroy (gameObject);
}
}
}
Put that script on the object you wish to spawn and quickly kill. You’ll have to spawn the object with another script or such though. You can change the amount of time it survives in the inspector.
EDIT: Wups, I see you already did all that. I should learn to read before I reply -facepalm-
Regardless I’ll leave the script here in case anyone else want’s to do something like that.