- Home /
Instantiate 4 prefabs at 4 locations, shuffled
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.
Answer by Larry-Dietz · Dec 20, 2017 at 06:28 PM
Try something like this...
public void Shuffle()
{
GameObject tmp;
for (int i = 0; i < 100; i++)
{
int a = Random.Range(0, platforms.Length);
int b = Random.Range(0, platforms.Length);
tmp = platforms[a];
platforms[a] = platforms[b];
platforms[b] = tmp;
}
}
Then add a call to Shuffle in start before your loop.
I haven't tested this. I normally use List instead of an array, and i know this method will work with a list. I just modified it for an array off the top of my head. If it doesn't work, let me know.
I'm always ending up with off by 1 errors, so if you get an index out of bounds error, change the .Length lines in the Random.Range to .Length - 1
Hope this helps, -Larry
I don't $$anonymous$$d using a list ins$$anonymous$$d of an array. How would go about creating this with a List, ins$$anonymous$$d of an Array?
Either way is fine.. But if you want to use a list, change your declaration to public List platforms = new List();
then in the Shuffle routine, change the .Length to .Count
Let me know if you have any problems with this. -Larry
It actually works both with Lists and Arrays! it's a great method, would you please explain how this exactly works? I'm having a hard time understanding it. Thanks!