Switch Statement Problem

I am trying to make one of three different coloured fish pop out at random every 3 seconds.
The issue w/ my code is that the same fish pops out every time. If I restart the level, i get a different fish, but as long as the level is running that fish is the only one that will come out. Here is my code.

3347859–261703–FishScript.cs (945 Bytes)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Timers;
using System;
public class FishScript : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(FishAppear());

}

// Update is called once per frame
void Update () {

}
IEnumerator FishAppear()
{
System.Random numberGenerator = new System.Random();
int fish = numberGenerator.Next(1, 4);
while (enabled)
{
yield return new WaitForSeconds(3f);
switch (fish)
{
case 1: Debug.Log(“Blue”);
break;
case 2: Debug.Log(“Orange”);
break;
case 3: Debug.Log(“Yellow”);
break;
// gives the same fish every time;
}
}
}
}

Put the :

int fish = numberGenerator.Next(1, 4);

inside the while (enabled)

Please look at this page for how to post code on the forums:

As methos5k is already pointing out, the problem is you’re only generating your random number once for the entire run of the coroutine instead of once per fish you want to generate.

Yes, as @methos5k and @Joe-Censored pointed out, that’s the issue.

Did it remind anyone of this classic?

1 Like