I have a GameController object with a GameController script that passes two GameObjects to a CombatManager script on the GameController. For some reason, after the GameObjects are passed, the CombatManager sees them as null, but only when I try to add them to a List. I don’t even know where to begin. I’ve tried accessing the “name” field of the GameObject, and I can access it just fine, meaning it’s not null, but when I try to put it in a List, I get a NullReferenceException!
Here’s my GameController (in C#):
public class GameController : MonoBehaviour
{
public GameObject combatant1, combatant2;
public CombatManager combatManager;
private void Start()
{
combatManager = gameObject.GetComponent<CombatManager>();
combatManager.SetCombatants(combatant1, combatant2);
}
}
Here’s my CombatManager (also in C#):
public class CombatManager : MonoBehaviour
{
private List<GameObject> combatants;
private void Start()
{
combatants = new List<GameObject>();
}
public void SetCombatants(GameObject combatant1, GameObject combatant2)
{
combatants.Add(combatant1); // Here is where Unity says the error is
combatants.Add(combatant2);
SortCombatantsBySpeed();
}
}
The exact error is this:
NullReferenceException: Object reference not set to an instance of an object
CombatManager.SetCombatants (UnityEngine.GameObject combatant1, UnityEngine.GameObject combatant2) (at Assets/Scripts/CombatManager.cs:16)
GameController.Start () (at Assets/Scripts/GameController.cs:13)