- Home /
The question is answered, right answer was accepted
Initiate class array at start and assign class values.
I am having problems instantiating a class array and assigning value at each instance of the class on Start. I am getting NullReferenceException: Object reference not set to an instance of an object. The bool and int assignement cause this problem.
Here is an exemple of what i am trying to achieve.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TESTER
{
public bool boolean = false;
public int interger = 10;
}
public class TEST : MonoBehaviour {
public TESTER[] testers;
void Start () {
testers = new TESTER[20];
Testing();
}
void Testing()
{
foreach(TESTER currentTest in testers)
{
currentTest.boolean = true;
currentTest.interger = 20;
}
}
}
Tester, being a reference type (class) will be null unless you initialize it. When you create a new array of 20 Tester, each element of the array is initially null.
You can initialize the array like this:
void Start () {
testers = new TESTER[20];
for (int i = 0; i < testers.length; i++)
testers[i] = new TESTER();
Testing();
}
Or alternatively, turn your Tester class into a struct.
Follow this Question
Related Questions
how can i check if there is a blanc spot in my list 3 Answers
How to hide/unhide an array of objects with a mouse click. 0 Answers
Add two radius on the same shader 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers