- Home /
Object reference not set to an instance of an object
When i cut down a tree i get "NullReferenceException: Object reference not set to an instance of an object cutTree.Update ()"
I dont know what i am doing wrong? This is my code:
var trees: GameObject[];
var bullitPrefab:Transform;
function Start() {
trees = GameObject.FindGameObjectsWithTag("Tree");
}
function Update() {
if(Input.GetButton("placeLog")) {
for(var tree in trees) {
if(tree == null)
continue;
if(Vector3.Distance(tree.transform.position, transform.position) < 5)
{
Instantiate(bullitPrefab, GameObject.Find("logSpawn").transform.position, Quaternion.Identity);
Destroy(tree);
break;
}
}
}
}
could i have some help please
$$anonymous$$ultiple questions is fine as long as they're not all the same thing.
But these are. I closed the older one.
@vicenti, you might want to know that there are 3 identical questions. Please close this one as well. I have add in the information from that question into this question.
@turbinator, I wouldn't eat a horrible-looking but edible food unless I have no choice. Please make your code cleaner and more presentable, those who will answer your question have a choice not to. I have formatted and clean up the codes for you this once.
Answer by Cygon4 · Apr 07, 2013 at 10:04 AM
NullReferenceException in general
You already have a check if(tree == null)
in there, so I assume you are knowledgeable enough to understand that variables like trees
and bullitPrefab
can be empty (eg. hold the value null
instead of an actual object).
If you try to call a method (`trees.Sort()`) or attempt to access a property (`tree.transform`) on an empty variable, you get a NullReferenceException
.
The easiest way to find such issues is by running your script with the MonoDevelop debugger attached because it puts you on the exact line where it occurred (Unity Documentation: Debugger). Attaching the debugger is currently a bit complicated, but knowing how to do it helps with lots of issues.
In your code
For the code you posted, trees
could be null
if there are no trees in your scene (because GameObject.FindGameObjectsWithTag() returns null
instead of a zero-length array if no game objects are found),
The inline call to GameObject.Find("logSpawn")
could return null
, too, and cause the exception.
Also, bullitPrefab
could be null, but I don't believe Instantiate would throw a NullReferenceException
when being handed a null
prefab.
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
I can do this in JS or not ??? 2 Answers
Script not working (Java script) 2 Answers