I'm trying to cycle through a 2D array of card objects and instantiate them in my Unity scene. However, I'm getting a Null reference exception when trying to instantiate them. Here is the code that instantiates the objects:
//Setting up initial board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++){
//Checked with debug.log, this should work Debug.Log (board[j, i].name);
Debug.Log(board[j, i].name);
temp = Instantiate(board[j,i]) as GameObject;
CardScript cs = temp.GetComponent<CardScript>();
objectBoard[j, i] = cs;
//Setting locations of the cards
objectBoard[j, i].transform.position = new Vector3(30 * j + 20, 50 * i + 70, 0);
}
}
The error occurs in the line 'CardScript cs = new.... I originally had the error in the temp = Instantiate... line, when the code was GameObject temp = Instantiate.... It fixed when I made temp a private GameObject variable in the code. I don't think I can do that with this one, because I need to have a reference to each individual object I'm instantiating.
Full Code:
public class MatchScript : MonoBehaviour {
public CardScript[] potentialCards;
private CardScript[,] board;
private CardScript[,] objectBoard;
private List<CardScript> entries;
private GameObject temp;
// Use this for initialization
void Start () {
entries = new List<CardScript> ();
objectBoard = new CardScript[4,3];
board = new CardScript[4, 3];
foreach (CardScript c in potentialCards)
entries.Add (c);
foreach (CardScript c in potentialCards)
entries.Add (c);
//Loading up the board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++){
int k = Random.Range(0, entries.Count);
board[j, i] = entries[k];
entries.RemoveAt(k);
}
}
//Setting up initial board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++){
//Checked with debug.log, this should work Debug.Log (board[j, i].name);
Debug.Log(board[j, i].name);
temp = Instantiate(board[j,i]) as GameObject;
CardScript cs = temp.GetComponent<CardScript>();
objectBoard[j, i] = cs;
//Setting locations of the cards
objectBoard[j, i].transform.position = new Vector3(30 * j + 20, 50 * i + 70, 0);
}
}
}
// Update is called once per frame
void Update () {
}