devklick
devklick

Reputation: 2638

While loop crashing Unity, but is not infinite

I'm aware (from similar posts) that infinite while loops are notorious for causing Unity3d to crash. I'm tring to impliment a while loop within something I'm working on, which I'm fairly sure isn't 'infinite', yet causes the game to crash.

The idea of the logic is to check a list of integers for consecutive numbers and use that as the basis to apply a bonus. The list contains 'effective shots', and has a new int added every time a shot is fired - the more consecutive effective shots, the higher the bonus.

Here's what I have:

        int count = 0;
        int firstItem = 0;
        int multiples = 3;
        int currentMultiple = 0;
        int bonusX = 0;

        foreach (int i in effectiveShots)
        {
            if (count == 0)
            {
                firstItem = i;
                count = 1;
            }

            else if (i == firstItem + count)
            {
                count++;
            }

        }

        while (count >= multiples)
        {
            currentMultiple = multiples;

            if (count == currentMultiple + multiples)
            {
                bonusX += 1;
            }

            if (bonusX > 10 || gameOver)
                break;

            UnityEngine.Debug.Log(bonusX);
        }

The logic to check for consective entries in the effectiveShots list was taken from @Jon Skeet's answer here. Though this appears to work, I think that this may be the issue. As soon as a shot is missed, count needs to be reset. Any ideas or suggestions?

The while loop should then be entered once the count of consecutive effective shots has reached the first multiple, i.e. 3 shots. Then, for every set of consequtive effective shots thereafter, increment the bonus, for example:

3 shots: bonusX = 1
6 shots: bonusX = 2
9 shots: bonusX = 3
12 shots: bonusX = 4

and repeat this until `count` is no longer >= 3, i.e. the player missed a shot. 

The issue is that as soon as I hit 3 consequtive shots and enter this loop, the game crashes. I dont think I would call this an infinite loop, since missing a shot - setting count == 0 - would mean the while conditions are no longer true, so drop out of the loop (I think?). I also added an additional check to break out of the loop under certain circumstances, but this doesnt make a difference.

If you are able to give a steer as to how to fix this crashing, or have a suggestion on a better approach in general, it would be appreciated!

Upvotes: 1

Views: 3988

Answers (1)

Mark Pim
Mark Pim

Reputation: 10074

Nothing in your while loop changes the value of either count or multiples and so the condition will always evaluate to the same value => Infinite loop

Upvotes: 5

Related Questions