- Home /
NullReferenceException: Object reference not set to an instance of an object
Hello,
I have 16 gameobjects using the same script MotionDetector and each store in the private int "k" the number each object is clicked.
I also have this script
using UnityEngine; using System.Collections;
public class SodokuPuzzle : MonoBehaviour {
MotionDetector[] myObjects;
void Start() {
myObjects = new MotionDetector[16]; // new array with 16 elements ( 0..15 )
for (int i = 0; i <= 15; i++)
{
GameObject go = GameObject.Find("B"+ (i+1));
if (go != null)
{ Debug.Log("got : "+i);
myObjects[i] = go.GetComponent<MotionDetector>();
}
else
Debug.Log("sommething if wrong");
}
}
// Update is called once per frame
void Update () {
if(myObjects[0].k+myObjects[1].k+myObjects[2].k+myObjects[3].k==10) //Check first rows sum is 10
{Debug.Log("first row corect");
}
else
{
Debug.Log("first row not corect");
}
if(myObjects[4].k + myObjects[5].k + myObjects[6].k +myObjects[7].k==10) //Check second rows sum is 10
{Debug.Log("Second row corect");
g++;
}
else
{
Debug.Log("second row not corect");
}
if(myObjects[8].k + myObjects[9].k + myObjects[10].k +myObjects[11].k==10) //Check third rows sum is 10
{Debug.Log("Third row corect");
g++;
}
else
{
Debug.Log("Third row not corect");
}
}
}
It comes up with the error: NullReferenceException: Object reference not set to an instance of an object SodokuPuzzle.Update () (at Assets/SodokuPuzzle.cs:65)
If I delete 2 out of the 3 if statements (in the update function) it works fine. Why would it work for 1 IF statement and not 2 or 3? Please help.
Which one is line 65 exactly? Also, which if statement do you remove? Where is g declared?
Not relevant to problem, but you have spelt the name of the game wrong: "Sudoku"
line 65 is if(myObjects[4].k + myObjects[5].k + myObjects[6].k +myObjects[7].k==10)
and g is irrelavent to the problem
THanks Julien I had duplicate name objects. I am just an idiot.
Trust me, everyone is an idiot sometimes when program$$anonymous$$g. I'm going to add the comment as an aswer below - if you approve it it will mark the question as answered.
Answer by Julien-Lynge · Apr 24, 2012 at 04:19 PM
The error is telling you that one of your references (variables) in line 65 is null. The the following debugging to see what reference is null:
if (myObjects[4] == null)
Debug.Log("4 is null");
if (myObjects[5] == null)
Debug.Log("5 is null");
if (myObjects[6] == null)
Debug.Log("6 is null");
if (myObjects[7] == null)
Debug.Log("7 is null");
if(myObjects[4].k + myObjects[5].k + myObjects[6].k +myObjects[7].k==10)