- Home /
Shuffle the positions of objects
Hi ! I try to make a shuffle function to Shuffle the positions of objects with an array. I made this little code work but it only shuffle the order of the elements in the array but not the positions of the objects themselves. I would really appreciate help for this ;) !
public class GMTrace : MonoBehaviour
{
[SerializeField] Transform[] Starts = new Transform[4];
[SerializeField] Transform[] Ends = new Transform[4];
private void Start()
{
ShuffleStarts();
}
private void ShuffleStarts()
{
for(int i =0; i<Starts.Length; i++)
{
int rnd = Random.Range(i, Starts.Length);
Transform temp = Starts[i];
Starts[i] = Starts[rnd];
Starts[rnd] = temp;
}
}
}
Answer by tyruji · Jul 22, 2021 at 12:48 PM
If you want to swap the positions, then:
the temp variable should be a Vector3 and should store Starts[ i ].position
do
Starts[ i ].position = Starts[ rnd ].position;
and Starts[ rnd ].position = temp;
That will "shuffle" the positions.
Your answer
Follow this Question
Related Questions
Recoil in Z axis 0 Answers
Problems setting up a counter for room randomization. 0 Answers
Spawning villages on random gen Terrain 1 Answer
Random AI patrol movement 3 Answers
Creating a Client based server Unity2D 0 Answers