I have 3 gameObjects created in my scene. And I have 3 Vector positions defined as well. I want to randomly assign each of these gameObjects to one of the positions. But no more than 1 gameObject should have same position as other. How do I use Random.Range() property here? Or is there a better approach?
public GameObject[] myObjs;
public Vector3[] myPos;
void Start(){
var number = Random.Range (0, myPos.Length);
}
CodePudding user response:
Simply shuffle one of the arrays and then assign them in order like e.g.
using System.Linq;
...
public GameObject[] myObjs;
public Vector3[] myPos;
void Start()
{
var randomPositions = myPos.OrderBy(n => Random.value).ToArray();
var amount = Mathf.Min(myPos.Length, myObs.Length);
for(var i = 0; i < amount; i )
{
myObjs[i].transform.position = randomPositions[i];
}
}
This simply uses Linq OrderBy
to sort the items of myPos
gien a certain order "property". Here we simply pass in Random.value
. => randomPositions
will contain all the item of myPos
exactly once but in random order. So then you can just iterate and assign them in a normal loop.