What's the difference?

I have two versions of the same code. One that i did myself and the other i got by following the course. Can someone please explain the difference because both codes are working perfectly fine. I just want to know if i would get any problems in the future with my code

MINE:

IEnumerator activateEnemy()
    {
        while (true)
        {
            for(int i = 0; i < pool.Length; i++)
            {
                pool[i].SetActive(true);
                yield return new WaitForSeconds(timePeriod);
            }
        }
    }

COURSE:

void enablePoolObject()
    {

        for (int i = 0; i < pool.Length; i++)
        {
            if (pool[i].activeInHierarchy == false)
            {
                pool[i].SetActive(true);
                return;
            }
        }
    }

    IEnumerator activateEnemy()
    {
        while (true)
        {
            enablePoolObject();
            yield return new WaitForSeconds(timePeriod);
        }
    }

What this code does is it enables the enemy from the object pool so that it can do the stuff its supposed to do. The activation is based on a coroutine that has a period defined by ‘timePeriod’

And there is something wrong going on. The objects are returning back to their starting position but they are still enabled. They are disabling randomly. :sneezing_face:

The main difference is that the course’s version checks all the objects and activates the first one it finds that’s not active. Then it waits before checking them all again. Yours goes through the list and activates each object and waits in between each. If the wait time is 5 seconds, the course’s code will activate an inactive object every 5 seconds. Yours cannot really be determined because you activate all objects and waits 5 seconds in between each. If you have a list of 10 objects of which the last 3 is inactive, the course will have all objects active within 15 seconds. Yours will take 50 seconds before all objects are active

Nothing in this code is disabling the objects. In fact, they are all getting enabled all the time. If anything anywhere disables them, this will just enable them again.

I think i get it. But even the course one isint working. But lemme check again :slight_smile:

How are you getting on with this, @Rustic_Dude?


See also:

Privacy & Terms