Hi guys,
New to unity and c#, I’m having trouble with a null reference exception which I have nailed down to a single line but I can’t see why it’s occurring.
I am trying to add a gameObject to a dictionary at a given key by invoking a function. When I do so with another object in the same way (as far as I can see) it works fine, but I’m getting a null reference exception when I try with another that I don’t know how to diagnose. I’ve narrowed it down to the line that’s producing the null reference, but my efforts to fix it haven’t gotten anywhere. Probably very simple for someone more familiar!
Line 11 in my entityAction script causes the exception. I’ve tried to cut out irrelevant code.
public class entityAction : MonoBehaviour
{
private Movement _movement;
private GameController _gameController;
void Start()
{
_gameController = GameObject.Find("GameManager").GetComponent<GameController>();
_movement = this.GetComponent<Movement>();
_gameController.addToQueue(1, this.gameObject);
}
}
public class GameController : MonoBehaviour
{
[HideInInspector]
public int globalTime;
public bool playerTurn;
public Dictionary<int, GameObject> turnQueue;
private GameObject player;
void Start()
{
globalTime = 0;
playerTurn = true;
turnQueue = new Dictionary<int, GameObject>();
player = GameObject.Find("Wanderer");
}
void Update()
{
if (!playerTurn)
{
globalTime++;
if(turnQueue.ContainsKey(globalTime))
{
Debug.Log(turnQueue[globalTime].name);
if (turnQueue[globalTime] == player)
{
playerTurn = true;
}
else
{
Debug.Log("entityTurn");
turnQueue[globalTime].GetComponent<entityAction>().Act();
}
}
}
}
public void addToQueue(int inTime, GameObject entity)
{
if(!turnQueue.ContainsKey(globalTime + inTime))
{
turnQueue[globalTime + inTime] = entity;
}
else
{
addToQueue(inTime + 1, entity);
}
}
}
Help would be greatly appreciated, I am still learning.