I am writing in Unity and not all classes can be instantiated as they inheriting Monobehaviour. I have several classes and am trying to Return an array to one class, but keep getting a null reference exception. I have made sure the array is indexed and initialized, yet it returns null. However in a same construction without an array, eg an Int, it works.
public class StartUp : MonoBehaviour //Unity class
{
public int x = 30,y = 30;
public PlayField entireField;
void Awake()
{
entireField = new PlayField(x,y);
entireField.InitArray(entireField, x, y);
}
}
public class CharacterController : MonoBehaviour
{
//edit: playField is not supposed hold value, just to get
//access to a method in PlayField
PlayField playField;
FieldData fData;
void Start(){
playField = new PlayField();
fData = new FieldData();
}
void Update(){
fData = playField.GetFieldData(5,6); //We're just telling it go to that method
}
}
public class PlayField
{
public SingleField[,] singleField;
public PlayField()
{
}
public PlayField(int x, int y)
{
singleField = new SingleField[x,y];
}
void InitArray(PlayField playfield, int x, int y){
//In an effort to save the data I also did
this.singleField = new SingleField[x,y];
for(int j ...
{
for (int x...
{
playfield.singleField[x, y] = new SingleField();
playfield.singleField[x, y].fielData = new FieldData();
playfield.singleField[x, y].fielData.height = GetRandom();
//and here
this.singleField[x,y] = new SingleField();
this.singleField[x,y].fieldData = new FieldData();
}
}
//to ..
this.singleField = playfield.singleField;
}
public FieldData GetFieldData(int x, int y){
//Here it keeps returning null reference
return this.singleField[x,y].fieldData;
}
}
public class SingleField
{
public FieldData fieldData;
public GameObject fieldObject;
}
public class FieldData
{
public float height;
public Vector3 position = new Vector3();
}
I know I can use a static variable but I'd like to know what I am doing wrong here or how I can get the values from entireField in StartUp class to the FieldData fData in CharacterController using the none-MonoBehaviour class PlayField? I thought the this.singleField-array would have values, but not during the Method call from CharacterController?