简体   繁体   中英

While loops in Unity C# making the PlayMode never load

I made this code:

public GameObject prefabBullet;
public GameObject[] places;

public int amountOfCycles;

public float baseTimeBetweenCycles;

public float timeBetweenCycles;

private int amountOfCyclesThatAlreadyHappened;

private int value = 0;

private int random;

void Start() {
    random = Random.Range(0, places.Length + 1);
    amountOfCyclesThatAlreadyHappened = 0;
}


void Update()
{
    while(amountOfCyclesThatAlreadyHappened < amountOfCycles)
    {
        while(value < places.Length && timeBetweenCycles < 0) 
        {
            if(value != random)
           {
            GameObject bulletGO = Instantiate(prefabBullet, places[value].transform.position, Quaternion.identity);
            timeBetweenCycles = baseTimeBetweenCycles;
           }
           value++;
           break;
        }

            if(timeBetweenCycles > 0)
           {
            timeBetweenCycles -= Time.deltaTime;
           }

            if(value > places.Length)
           {
               amountOfCyclesThatAlreadyHappened += 1;
               random = Random.Range(0, places.Length + 1);
               value = 0;
           }
    }

}

i do not think I did one of those loops infinite, as it sets eventually the value to 0 and both lops should eventually stop being true, as ++ exists in both loops. Anyone could tell me what is causing those loops to be infinite?

Your outer while is looping forever because amountOfCyclesThatAlreadyHappened never increments.

The only place in your code where amountOfCyclesThatAlreadyHappened could conceivably increment is inside this case: if(value > places.Length)

However, that case occurs inside a while loop with condition while(value < places.Length && timeBetweenCycles < 0)

As you can see, your if and while conditionals have opposite conditions relating to value, so the only way the inner if would ever be true is if value changed during loop execution before you hit that if block. However, the only place this happens, value++; , has a break; immediately after it so the loop doesn't continue on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM