This error is called a Null Reference Exception (which is the first half of the editor’s error message). It happens when you tie an object of any type to a variable, and later on try to access it but for some reason it doesn’t exist anymore. For example saving a reference of a cube in your scene on a GameObject variable in-script, then destroying the cube with Destroy( ) and subsequently trying to do something with the GameObject variable, which is now null, since the cube it referenced isn’t in the scene any longer.
In your case, you’re trying to instantiate a prefab to the position of an object in the scene (logSpawn) which you try to find with GameObject.Find( ). However, logSpawn might not be there at the point where you try to access it, thus returning a null value. However, your code isn’t prepared to handle such a case, and attempts to access the null value as if it was logSpawn, leading to the error. We handle exceptions like these with either try/catch or with if statements. I prefer to use if statements myself for such simple code. Your instantiate code by this logic should look like this :
Just to add to this, he really should be caching the logSpawn in Start(), as Find is quite intensive, and its bad practice to use it in Update, even if it is rarely used.
He should only cache it if logSpawn isn’t destroyed and respawned (which the error message suggests it happens). Otherwise he will have a reference to an object he might not even want, if it exists at all.
i have tried the code above but its still giving me the same error when i try to cut a tree:NullReferenceException: Object reference not set to an instance of an object
cutTree.Update ()
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) {
var logSpawn : GameObject = GameObject.Find("logSpawn");
if(logSpawn) {
Instantiate(bullitPrefab, logSpawn.transform.position, Quaternion.Identity);
Destroy(tree);
break;
}
}
}
}
}