Infinite loop problem

Hello! This code works, but when the array is empty, as in no elements were added from the inspector, unity enters an infinite loop and the only option is to shut it down. Any ideas? Thanks in advance!

    private bool PreviousArrayContainsAudioClipIndex()
    {
        for (int i = 0; i < previousArray.Length; i++)
        {
            if (previousArray[i] == audioClipIndex)
            {
                return true;
            }
        }
        return false;
    }  

private AudioClip GetClipNullClips()
    {
           return GetClipFrom(NullClips);
    }  

private AudioClip GetClipFrom(AudioClip[] clips)
    {
        if (previousArray == null)
        {
            previousArray = new int[clips.Length / 2];
        }
        if (previousArray.Length == 0)
        {
            // If the the array length is 0 it returns null
            return null;
        }
        else
        {
            // Psuedo random remembering previous clips to avoid repetition
            do
            {
                audioClipIndex = Random.Range(0, clips.Length);
            }
            while (PreviousArrayContainsAudioClipIndex());
            // Adds the selected array index to the array
            previousArray[previousArrayIndex] = audioClipIndex;
            // Wrap the index
            previousArrayIndex++;
            if (previousArrayIndex >= previousArray.Length)
            {
                previousArrayIndex = 0;
            }
        }
        // Returns the randomly selected clip
        return clips[audioClipIndex];
    }

I’ve made this blunder more than once…check lines 32-36!

If your code loops until it picks a fresh random number, and there’s only one possible choice, then you’ll get stuck forever.

Random.Range(0,0) apparently returns 0, rather than throwing an exception. So, whether you have zero items or one item, it’ll randomly pick 0 forever and ever.

You should add a special case for when there are zero or one clips to choose from.

Unity will lock up 100% of the time EVERY millisecond your scripting code is running.

Nothing will render, no input will be processed, no Debug.Log() will come out, no GameObjects or transforms will appear to update.

Absolutely NOTHING will happen… until your code either:

  • returns from whatever function it is running

  • yields from whatever coroutine it is running

As long as your code is looping, Unity isn’t going to do even a single frame of change. Nothing.

No exceptions.

“Yield early, yield often, yield like your game depends on it… it does!” - Kurt Dekker