Search code examples
unity-game-enginedestroy

Increase time until destroying prefab


I am firing a ball of sticky goo. In my onStart() I am calling Destroy(Goo, 5f) which will destroy it after 5 seconds from when it was created.

However, I have an onTriggerEnter() that is being called when the goo hits the main character. In this case - I want to prolong the life of the goo for an extra 5 seconds.

Is there any way I can do this?


Solution

  • I'm not sure if Unity has anything like this built in, but you could simply use your own internal timer rather than calling a delayed destroy.

    void onStart()
    {
        mDestroyTimer = 5.0f;
    }
    
    void Update()
    {
        mDestroyTimer -= Time.deltaTime;
        if (mDestroyTimer <= 0)
        {
            Destroy(Goo);
        }
    }
    
    onTriggerEnter()
    {
        mDetroyTimer += 5.0f;
    }
    

    I'm sure it's possible to come up with a more elegant solution but this should give you good control over the lifespan of the Goo object.