NullReferenceException: Object reference not ... ( Assistance please )

Hi Guys

I seem to be missing something here. I get NullReferenceException: Object reference not set to an instance of an object SmoothFollowDelayed.Update () (at Assets/Scripts/SmoothFollowDelayed.js:13)

Line 13 is Var findtarget. it happens when the player gets destroyed.

function Update () {
var findTarget = GameObject.FindWithTag ("Player").transform;
  if (findTarget!=null){
  target =  findTarget;
  }else{return;}
}

it happens when the player gets destroyed.

GameObject.FindWithTag ("Player")

That will return null.

GameObject.FindWithTag ("Player").transform

This will be like saying

null.transform

You can’t get a transform of null or “nothing”.

You can fix it by breaking up the chain.

function Update() {
   var findTarget = GameObject.FindWithTag ("Player");

   if (findTarget == null) // ... or if (!findTarget)
       return;

    target = findTarget.transform; // NOW it is safe to access transform.
}

The problem is that update is being performed while your GameObject tagged player is gone/destroyed. When it’s destroyed you will be unable to get the transform member of that GameObject. Perhaps it’s better to get the GameObject first, check for null and then get the transform values.

Example:

function Update () {
	var findTarget:GameObject = GameObject.FindWithTag ("Player");
	// If the gameobject isn't null then Vector2/Vector3 structs will always have a default value.
	if (findTarget != null){
		target =  findTarget.transform;
	}
	else
	{
		return;
	}
}