Custom class instance always return null
Edit: It's quite weird, I put a Debug.log in the Update function in DataControl, the list seems to maintain it's length but lost all of it's contents after scene switch. (The list has length of 0 when initialized)
So i created this custom class shown below:
public class FormationCommand : MonoBehaviour {
public Vector3 posOffset;
public Quaternion rotation;
public FormationCommand(Vector3 _posOffset, Quaternion _rotation){
//this.name = "FC_Name";
this.posOffset = _posOffset;
this.rotation = _rotation;
}
}
And i assigned it like this: the following code is called when ever an agent (the triangle in the picture below) is placed. But as you can see in the inspector (Also in picture) the commandForAgents list is always having "None (Formation Command)" in list.
FormationCommand currentFormationCommand = new FormationCommand((gridPos - leader.position), Quaternion.identity);
DataControl.dataControl.commandForAgents.Add (currentFormationCommand);
And also, in DataControl class, the commandForagents is defined like this:
public List<FormationCommand> commandForAgents;
void Start(){
commandForAgents = new List<FormationCommand> ();
}
More Information:
The DataControl is a DontDestory gameobject that pass data between scenes, in my scene 1 player define the commandForAgents and in scene 2 player use it.
I used following code to test the value of commandForAgents. But they result differently in different scene. In Scene 1, i test it right after i define it, it prints me perfect results. But in scene 2 it give me "NullReferenceException: Object reference not set to an instance of an object"
foreach (FormationCommand fc in DataControl.dataControl.commandForAgents){
//NullReferenceException: Object reference not set to an instance of an object
Debug.Log (fc.posOffset);
}
Any suggestions would be appreciated !
Answer by libra34567 · Dec 08, 2016 at 03:45 AM
Turns out the problem is that FormationCommand is a monobehavior class, which doesn't support new keyword as well as constructor. remove monobehavior to make it a regular class will solve the problem.