Search code examples
c#unity-game-engineinstantiation

Instantiate 4 prefabs at 4 locations, shuffled, Unity Engine C#


What I have are 4 platforms that I instantiate at 4 locations. What I want is for the platforms to be shuffled every time. My code so far:

using UnityEngine;

public class PlatformCreator : MonoBehaviour {

 public GameObject[] platforms;
 public Transform[] points;

 private void Start()
 {

     for (int i = 0; i < points.Length; i++)
     {
         Instantiate(platforms[i], points[i].position, Quaternion.identity);
     }
 }

}

For example the platforms now always spawn in the same order - pink, yellow, blue, purple

I want them to be spawned in different order every time, for example - yellow, blue, purple, pink. I've tried creating an int index with random.range, but I am messing something up


Solution

  • You could add the points to a List instead of an array, which will help you to "shuffle" the values. Taking the shuffle function from This SO post, you could do something like this:

    public class PlatformCreator : MonoBehaviour {
    
     public GameObject[] platforms;
     public List<Transform> points;
    
     private Random rng; 
    
     public void Shuffle<T>(this IList<T> list)  
     {  
        int n = list.Count;  
        while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
        }  
     }
    
     private void Start()
     {
        rng = new Random(); 
        points.Shuffle();
        for (int i = 0; i < points.Count; i++)
        {
            Instantiate(platforms[i], points[i].position, Quaternion.identity);
        }
     }
    }