Problems with arrays

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!

Try this in the start function, don’t initialize where you are declaring the array.

PrefabArr = Resources.LoadAll(“Prefabs”) as GameObject[ ];

New Error. Doesn’t know what PrefabArr is. If I put it in its original spot and in the start function, I get a Null Reference Exception.

Ok my bad I assumed you knew that you first need to declare the array, and then initalize it.

So first declare it outside any function like this

GameObject[ ] PrefabArr ;

then initialize in start function

void Start()
{
  PrefabArr = Resources.LoadAll("Prefabs") as GameObject[];
}

Hmm. Well I get no compiler errors now, but it doesn’t work. I can only think of 2 possible reasons why:

  1. “NullReferenceException: Object reference not set to an instance of an object” comes up
  2. Perhaps it can’t access my Prefabs for some reason? I have them setup like this:
    Assets>Resources>Prefabs
    Then in that folder are 4 Prefabs.
    circle_a_blue_1
    circle_b_blue_3
    circle_c_blue_3
    circle_d_blue_1

Something isn’t connecting. Looking under the Prefab Arr variable while the script is running shows Size = 0. It doesn’t even look like an array.

Do this instead, it should work just fine.

void Start() {
    PrefabArr = Resources.LoadAll<GameObject>("Prefabs");
    
    // get random prefab
    GameObject myGo = PrefabArr[Random.Range(0, PrefabArr.Length)];
}

Cool. I’ll try that when I get home. I’m on a paid 3D Maya project.

One question is how do I factor in the probability that one piece will spawn over another? See my first post to see what I was trying to accomplish.

That worked well, but I made 1 edit. Instead of using the Start function, I moved everything into a function to be accessed by a CoRoutine that I use on start.

//Spawn Controller
	void SpawnStart() {
		    // Define Prefab Array
		    PrefabArr = Resources.LoadAll<GameObject>("Prefabs");
			// get random prefab
			int randomSpwn = Random.Range(0, PrefabArr.Length);
			//instantiate Prefab
			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);
		}
	}

Now I have to figure out how to factor in spawn probability of a specific piece. Each prefab has a component called Piece Score that carries the variable called chance. I want to see if I can figure that into the equation when spawning.