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

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.