1

Here is my code:

public class RandomNumbers : MonoBehaviour {
    public Transform mCanvas;
    public Text[] numbers;
    int idx = 0;

    void Start()
    {
        StartCoroutine("CreateNum"); 
    }

    IEnumerator CreateNum()
    {
        while (idx < numbers.Length)
        {
            Text g = Instantiate(numbers[idx], new Vector3(Random.Range(-100, 100), Random.Range(-100, 100), 0), Quaternion.identity);
            g.transform.SetParent(mCanvas, false);
            yield return new WaitForSeconds(2f);
            Destroy(g);
            ++idx;
        }
    }
}

This code makes 4 texts appear in ascending order on the screen. I want these four numbers to appear not in increasing but random form.

Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63

1 Answers1

2

What you need to do is shuffle the array of numbers so they are in a random order, then you can grab in order the randomized list and it acts the same as picking items at random without duplicating.

public class RandomNumbers : MonoBehaviour {
    public Transform mCanvas;
    public Text[] numbers;
    int idx = 0;

    void Start()
    {
        //Randomizes the list of numbers
        Shuffle(numbers);

        StartCoroutine("CreateNum"); 
    }

    IEnumerator CreateNum()
    {
        while (idx < numbers.Length)
        {
            Text g = Instantiate(numbers[idx], new Vector3(Random.Range(-100, 100), Random.Range(-100, 100), 0), Quaternion.identity);
            g.transform.SetParent(mCanvas, false);
            yield return new WaitForSeconds(2f);
            Destroy(g);
            ++idx;
        }
    }

    //This is called a Fisher-Yates shuffle https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
    //This function can be used with any Array or List you send it.
    private static void Shuffle<T>(IList<T> list)  
    {  
        int n = list.Count;  
        while (n > 1) {  
            n--;  
            int k = Random.Range(0, n + 1);  
            T value = list[k];  
            list[k] = list[n];  
            list[n] = value;  
        }  
    }

}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431