- Home /
Null reference solved, other issue resolved by user.
NullReference exception problem
Hi
I have the following code which produced the error "NullReferenceException: Object reference not set to an instance of an object" at the line where I try to enqueue one of the linkedDialogues but I'm not sure why I am getting the error because if I log the object I seem to be able to access it. The Dialogues extend ScriptableObject. I'm not sure if this is the problem. Any ideas anyone?
float currentPosX = 20.0f;
Queue<Dialogue> queue = new Queue<Dialogue>();
queue.Enqueue(workingSequence.RootDialogue);
while(queue.Count > 0)
{
Dialogue currentDialogue = queue.Dequeue();
if(currentDialogue == null)
{
Debug.Log("null");
continue;
}
for (int index = 0; index < currentDialogue.linkedDialogues.Count; index++ )
{
if (currentDialogue.linkedDialogues[index] != null)
{
Debug.Log(currentDialogue.linkedDialogues[index].name);
//ERROR IN THIS LINE BUT CAN ACCESS OBJECT WITH ABOVE LOG STATEMENT
queue.Enqueue(currentDialogue.linkedDialogues[index]);
}
}
nodes.Add(new DialogueNode(currentDialogue, this, nodes.Count + 1, new Rect(currentPosX, 20, 400, 0)));
currentPosX += 200.0f;
}
Answer by Chris D · Jul 22, 2011 at 04:40 PM
Won't
for(int index = 0; index < currentDialogue.linkedDialogues.Count; index++ )
go beyond your index by one (because of 0-indexing)?
for(int index = 0; index < currentDialogue.linkedDialogues.Count-1; index++ )
instead.
Although that wasn't the route of my problem because I was getting an exception with all references, your right that did cause an exception but an out of range exception. It turned out the I was doing something random in the lists getter function so I've solved the issue now thanks.
Edit: Sorry about posting as an answer I was responding through my mobile and got confused. Anyway I was going to tick your answer but as my title is asking about the null reference exception and your answer was about the loop possibly going out of range I thought it would be best not to tick it to save confusion. Its probably a better idea to close the question to answers as I solved the original question myself but I don't have the power to do so.