1

I made a script which displays random image from the list every X seconds, but sometimes it shows the same image over the course of hours of gameplay. I was wondering how would I go about making it not show the image that has already been shown during current game session. Here's my code:

void Start () {

        // start count
        StartCoroutine(RandomReportEvent());

}

xx

IEnumerator RandomReportEvent(){


        float wait_time = Random.Range (53.5F, 361.2f); // removed 1879.2f

        // test purposes
        // float wait_time = Random.Range (1.7F, 3.2f);

        yield return new WaitForSeconds(wait_time);
        memeWindow.SetActive (true);

        // get random reports number within range
        float ReportValue = Random.Range (1.2F, 57.8F);

        // round to 2 dp
        ReportValue = Mathf.Round(ReportValue * 100f) / 100f;
        // show random report value in Text
        randomReportValue.text = string.Format ("<color=#FF8400FF>{0}K</color>", ReportValue);

        // Show Random Image from list
        showRandomImage();
    }

xx

void showRandomImage(){

        // count the amount of images 
        int count = memeImg.Count;

        // randomly select any image from 0 to count number
        int index = Random.Range(0, count);

        // assing an image from our list
        sr.sprite = memeImg[index];


    }

Any help would be appreciated!

Arthur Belkin
  • 125
  • 1
  • 10

2 Answers2

4

I suggest you make a list of all images, randomize the order of the list, and then just loop through it. When you reach the end, you can either re-shuffle or just restart the same sequence.

You can find a good way to shuffle a list or array in this answer.

gnud
  • 77,584
  • 5
  • 64
  • 78
4

What about creating a list of the images you have, then select a random image with your int index = Random.Range(0, count); from that list, after that you remove that item from the list with yourImagesList.RemoveAt(index); so in the next iterations the image is not going to be available. You can update the value of int count = memeImg.Count; with List<T>.Count after removing the image from the list. Sources: https://msdn.microsoft.com/en-us/library/5cw9x18z(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/27b47ht3(v=vs.110).aspx

Towerss
  • 629
  • 2
  • 12
  • 26