Question by
SeanHerriott · May 08, 2019 at 09:48 PM ·
instantiatearray of gameobjects
How to instantiate an array of prefabs into an array of empty gameobject positions
Firstly I'm a complete Noob. I'm trying to instantiate an array of prefabs into a predefined array of positions randomly. The element I'm trying to get with the PositionOFPlaceholders is a value for "pos" so that when I Instantiate the GameObjects, it will bring in my 34 prefabs into the 34 placeholders randomly. I'm getting the "Array out of Range" exception at this line;
placeholders[rndpos].transform.position = placeholderPositions[i];
Here is my code so far;
public class TileScript : MonoBehaviour {
public GameObject[] movableTiles;
private GameObject tempGO;
public Vector3[] placeholderPositions;
public GameObject[] placeholders;
private Vector3 pos;
void Start()
{
Shuffle();
PositionOfPlaceholder();
Instantiate(tempGO, pos, Quaternion.Euler(0, Random.Range(0, 4) * 90, 0));
}
public void Shuffle()
{
for (int i = 0; i < movableTiles.Length; i++)
{
int rnd = Random.Range(0, movableTiles.Length);
tempGO = movableTiles[rnd];
movableTiles[rnd] = movableTiles[i];
movableTiles[i] = tempGO;
}
}
public void PositionOfPlaceholder()
{
placeholders = GameObject.FindGameObjectsWithTag("Placeholder");
for (int i = 0; i < placeholders.Length; i++)
{
int rndpos = Random.Range(0, placeholders.Length);
pos = placeholders[rndpos].transform.position;
placeholders[rndpos].transform.position = placeholderPositions[i];
placeholderPositions[i] = pos;
}
}
}
Any ideads?
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612201009im_/https://answers.unity.com/themes/thub/images/avi.jpg)