- Home /
Why am i getting a null reference?
My Script is:
void DestroyBlock ()
{
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, range))
{
if (hit.collider.transform.parent.tag == "Block")
{
Destroy(hit.collider.transform.parent.gameObject);
Vector3 hitPos = hit.collider.transform.parent.transform.position;
int x = (int) hitPos.x;
int y = (int) hitPos.y;
int z = (int) hitPos.z;
Destroy(levelData[x, y, z].gameObject); *** this is where the error is
dataScript.levelData = levelData;
}
}
}
null reference exception: object reference not set to an instance of an object
No one will be able to help you pinpoint the problem here. The problem is not always where you are getting the error, but sometimes where the object is created in this case.
In the eample you provided I do not see where levelData is declared and set. Can you post the code where you populate the data in levelData?
you point out the error but what does levelData look like? you should include that too.
Does levelData exist, is it filled, and does it have a set size?
Can you tell us the line that causes the error please?
Double clicking on the error in Unity Console window should take you to the exact line in code where the error happens. From there it should be pretty easy to deduct the reference that's causing the error.
have you tried doing prints just before the error? like:
print(levelData[x, y, z]); print(levelData[x, y, z].gameObject);
Answer by thepenguinmaster · Dec 09, 2014 at 02:27 PM
levelData[x, y, z] is throwing an error because you never declared the variable. Also you need to set data into the array. It is likely that where you are populating the data, one of the objects is null. Given the code you posted, there is no way for us to provide further help.
The code you posted is where you see the error, but not where the error is caused. You will need to post the code where the array is declared, and the values are set into the array, then we may be able to help.
Your answer
Follow this Question
Related Questions
missing gameobject ≠ Null? 1 Answer
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Instantiating prefabs: "The object of type GameObject has been destroyed". 1 Answer
Object reference not set to an instance of an object (with a RaycastHit) 3 Answers
Can't destroy objects 1 Answer