John Smith
John Smith

Reputation: 75

How to destroy an object after few seconds when it spawns?

I'm having trouble with destroying spawning cloned objects. It does not destroy it.

I am using prefabs (health, armour...) and empty game objects as spawn points.

It spawns it and everything is okay, but I do not destroy it. So my question is: How to destroy a child of an object? (second "if" in update function!).

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

public class SpawnObjects : MonoBehaviour
{

    public Transform pickUp;
    public Transform[] spawnPoints;
    public float Timer = 10;
    public float Timer1 = 15;

    void Start()
    {
        if (spawnPoints.Length == 0)
        {
            Debug.LogError("No spawn points referenced.");
        }
    }

    void Update()
    {
        Debug.Log("Spawning: " + pickUp.name);
        Timer -= Time.deltaTime;
        Timer1 -= Time.deltaTime;

        if (Timer <= 0)
        {
            Transform _sp = spawnPoints[Random.Range(0, spawnPoints.Length)];
            Instantiate(pickUp, _sp.position, _sp.rotation);
            Timer = 10;

        }

        if(Timer1 <= 0)
        {
            //Destroy(pickUp);
            Timer1 = 15;
        }
    }
}

Upvotes: 0

Views: 1458

Answers (2)

Lars
Lars

Reputation: 1

You can write in you Start function Destroy(gameObject, 15); gameObject is the gameObject you want to destroy, 15 the is amount of seconds you want to 'keep it alive'.

Upvotes: 0

Hellium
Hellium

Reputation: 7346

Destroy accepts a second argument to delay the effective destroy

public class SpawnObjects : MonoBehaviour
{

    public Transform pickUp;
    public Transform[] spawnPoints;
    public float Timer = 10;

    void Start()
    {
        if (spawnPoints.Length == 0)
        {
            Debug.LogError("No spawn points referenced.");
        }
    }

    void Update()
    {
        Timer -= Time.deltaTime;

        if (Timer <= 0)
        {
            Transform _sp = spawnPoints[Random.Range(0, spawnPoints.Length)];
            GameObject instance = Instantiate(pickUp, _sp.position, _sp.rotation).gameObject;
            Destroy(instance, 15);
            Timer = 10;
        }
    }
}

Upvotes: 2

Related Questions