Stumped as usual. I’m trying to get all my prefabs to load into an array so I can have unity randomly pick from the array a random one to instantiate. However I am getting an IndexOutOfRange Exception. Here is my code:
using UnityEngine;
using System.Collections;
using System.Threading;
public class SpawnPieces : MonoBehaviour {
//Sets up prefab
public GameObject Spawner; //deines the empty Game Object that will spawn the pieces
public float fSpawnDelay; //Indicates the delay between each piece
// number of rows and columns
// use rows to count pieces
public int rows = 8; //Rows horizontal
public int columns = 5; //Rows vertical
// load all prefabs into array
public GameObject[] PrefabArr = Resources.LoadAll("Prefabs") as GameObject[];
// Randomizer
public int randomLow = 0;
public int randomHigh = 3;
private int randomSpwn = Random.Range(1,1);
// count each row by GameTag
private int piececountR1 = GameObject.FindGameObjectsWithTag("game_piece_r1").Length;
private int piececountR2 = GameObject.FindGameObjectsWithTag("game_piece_r2").Length;
private int piececountR3 = GameObject.FindGameObjectsWithTag("game_piece_r3").Length;
private int piececountR4 = GameObject.FindGameObjectsWithTag("game_piece_r4").Length;
private int piececountR5 = GameObject.FindGameObjectsWithTag("game_piece_r5").Length;
//Spawn Controller
void SpawnStart() {
Instantiate(PrefabArr[randomSpwn], Spawner.transform.position, Quaternion.identity);
}
//Start Game Spawner Coroutine
IEnumerator StartGame() {
for(int i=0; i<rows; i++) {
SpawnStart();
yield return new WaitForSeconds(fSpawnDelay);
}
}
// Use this for initialization
void Start () {
//Run Coroutine
StartCoroutine(StartGame());
}
// Update is called once per frame
void Update () {
}
}
And for fun later, I have to reference this code on each prefab to figure in the probabality that it will spawn:
public class PieceScore : MonoBehaviour {
public string shape = "circle";
public string letter = "a";
public string color = "blue";
public int score = 1;
public int chance = 1; // This adds to spawning fun and headaches
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
So yes I’m doing something wrong. Can’t figure it out. I’ve never been very good with arrays. They never work right for me in any programming language I’ve ever tried. That is why I became a 3D guy, lol. Any hints would be great!