(Coroutine + do{} while()) vs. else if()

Question about Unity with 2D, laser defender, episode 102.

Rick makes a looping wave (or series of waves) by making start of type IEnumerator, and having it call the spawn all waves coroutine while bool looping is true.

I made a similar system prior to the episode (but made it in my wave manager so it could be checked by wave rather than by level) using an else if statement during the enemy Move() method. Here is the code I used:


private void Move()
{
if (waypointIndex <= waypoints.Count - 1)
{
var targetPos = waypoints[waypointIndex].transform.position;
var frameSpeed = waveConfig.GetMoveSpeed() * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPos, frameSpeed);

        if (transform.position == targetPos)
        {
            waypointIndex++;
        }
    }


    else if (waveConfig.loopWave == true)
    {
        waypointIndex = 0;
        var frameSpeed = waveConfig.GetMoveSpeed() * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, waypoints[waypointIndex].transform.position, frameSpeed);
    }

    else
    {
        Destroy(gameObject);
    }

So, what is the benefit of using a coroutine with do{} while() rather than a system like this to make waves loop?
Should I change my code, or is functionality going to be roughly equal here?

(Also, doesn’t this code allow for some enemies to be destroyed ie Galaga, while still looping the wave pattern with only the remaining enemies?)

Hi,

Welcome to our community, and good job on developing your own solution! :slight_smile:

In many cases, there is more than one way to make things work in Unity. If your solution solves the problem, it is valid by definition. Are you happy with your approach? If so, keep it. :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms