Why am I getting a null reference exemption on an if statement checking whether a value is null? That’s confusing to me. If I say “if (x)”, and x is null, why give me a null reference exemption? I’m even getting this problem when I make it clearer, as in “if (x != null)”. I don’t get it.
Here’s the offending code.
if (GameObject.FindWithTag("Player").transform != null){
target = GameObject.FindWithTag("Player").transform;
}
}
And here’s the whole script:
function Start(){
if (GameObject.FindWithTag("Player").transform)
{
target = GameObject.FindWithTag("Player").transform;
}
}
var target : Transform;
var x;
var y;
var z = -10;
function LateUpdate () {
if (target){
x = target.position.x;
y = target.position.y;
transform.position = Vector3(x,y,z);
}
}
I’m using it as a precaution for a camera follow script. It only tries to follow if the target is assigned, which works fine. But I wanted to assign the target in the script, and also have the precaution that the target would only assign if said object exists. I just don’t know why it’s giving me an error that something is null when I’m specifically using the if statement to check whether it’s null.
When I used “if (target)” it worked just fine, but for the other one it didn’t.
Any help would be appreciated.