Is this a valid algorithm for respawning an animated enemy?

I'm simply randomizing the position of an enemy after it has received a certain amount of damage. I'm wondering if this is a correct way of thinking about it:

In the enemy script:

  1. set the gameObject to be inactive ( = false)

  2. randomize it's position

  3. restart any animations (animation.Rewind())

  4. wait for a length of time (yield WaitForSeconds(x))

  5. set the gameObject to be active ( = true)

Now, I wouldn't be asking this if it were working properly, so obviously my thinking is wrong somewhere. I was hoping to use this approach to save on Destroying and Instantiating objects all the time.

It's not, no

When you set the gameObject inactive, it stops coroutines from running, which stops it working

What I personally do for stuff like this is have an empty gameobject with a script on which lets you start coroutines statically from any script


var instance : MonoBehaviour;

function Awake()
    instance = this;

static function StartRemoteCoroutine(coroutine : IEnumerator) : Coroutine
    return instance.StartCoroutine(coroutine);

Then you'd just use this to start your coroutine from your enemy (in semi pseudo js):

function Start()
    //set the gameObject to be inactive ( = false)
    //randomize it's position
    //restart any animations (animation.Rewind())

    //change CoroutineManager to the name you choose for the above script

function MyCoroutine()
    yield WaitForSeconds(x); = true;