- Home /
instantiate random object in Specified positions?
hello I have 14 different cubes and want to randomly put them in specified 15 positions one of that positions should be empty. how can I do that!? please javascript thanks
Comment
Best Answer
Answer by Tomer-Barkan · Nov 25, 2013 at 09:10 AM
You can put all your possible positions in a list, then choose one randomly, spawn the cube there, and remove it from the list. Until one remains:
public Vector3[] positions = new Vector3[15];
public GameObject cubePrefab;
public void Start() {
List<Vector3> positionsList = new List<Vector3>(positions); // convert possible positions to list
// iterate as long as more than one position remains
while (positionsList.Count > 1) {
int chosenPositionIndex = Random.Range(0, positionsList.Count); // choose random position from list
GameObject.Instantiate(cubePrefab, positionsList[chosenPositionIndex], Quaternion.identity); // create a cube at position
positionsList.RemovaAt(chosenPositionIndex); // remove position from list
}
}
Be sure to put the possible positions in the inspector, and the prefab for the cube.
You copied something wrong.
positionsList should be a List
not a Vector3[]
.
When you create a script via unity it automatically adds the using clauses to include the unity libraries. Use those.