Quick Question: Destroy spawned Object

Hey there, I’m an absolute noob, when it comes to programming but I need to learn it to program a simple game for my Bachelor Thesis.

What I’m trying to do, is letting an object spawn in a set interval and letting it disappear shortly after each spawn.
What happens instead, is that after the time that is set by the Despawntimer, the object just stops spawning and those that already did don’t disappear.

I’d tried it with the following code:

{
    public GameObject HilfeSchriftzug;
    public int Hilfes = 2;
    public float timer = 0;
    public float Despawntimer;

    void Start()
    {
        
    }

    void Update()
    {
        timer = timer + Time.deltaTime;
        if (timer < Hilfes)
        {

        }
        else
        {
            Instantiate(HilfeSchriftzug, transform.position, Quaternion.identity);
            timer = 0;
            Destroy(HilfeSchriftzug, Despawntimer);
        }

    }
}

Would be awesome if somebody could help me with this issue :slight_smile:

1 Answer

1

Hello @corniking,

When Instantiating an object you use a prefab (which is an asset in your project window, and when destroying the object you should destroy the instantiated gameObject, not the prefab, with your current code you can do like this:

public GameObject HilfeSchriftzug;
public int Hilfes = 2;
public float timer = 0;
public float Despawntimer;

private GameObject _unit; // You add a GameObject variable to keep a reference on the instantiated unit

void Update()
{
    timer = timer + Time.deltaTime;
    if (timer >= Hilfes) {
        this._unit = Instantiate(HilfeSchriftzug, transform.position, Quaternion.identity);
        timer = 0;
        Destroy(this._unit, Despawntimer);
    }

}

Thank you very much, that helped a lot! :) Just a quick follow up question: What exactly is the function of "this"? Haven't seen it yet and tried the code without it and it worked anyway.

"this" is a keyword, it's a reference on the current class, I got used to use it to discern local variable from class variable and same with function, but it's just a habit it doesn't change anything to the code or the logic

Alright, good to know. Thanks again!