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;}
}
Answer by Statement · Oct 26, 2015 at 01:08 PM
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.
}
Answer by Landern · Oct 26, 2015 at 01:09 PM
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;
}
}
// If the gameobject isn't null then Vector2/Vector3 structs will always have a default value.
?
$$anonymous$$eaning you can safely get the Vector value of a member if the GameObject isn't null since they are not reference types and not nullable in this case.