Why am I getting a null reference exemption?

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.

Problem is, you might not have a Game Object tagged “player” active. You can’t get the Transform of something that isn’t a Game Object.

private var target;

function Start() {
	var player = GameObject.FindWithTag("Player");
	if (player) target = player.transform;
}

var z : float;
function LateUpdate () {
	if (target) transform.position = Vector3(target.position.x, target.position.y, z);
}

I know, but that’s sort of the point. I’m checking to see if there is an object with that tag active.

Is there any way to do that in the script?

checks your code

…damn you’re good. :smile: I think it worked!

Also, it’s interesting to see just how much a more experienced coder can optimize even the things you think you did right. Looking at that, I’m hitting myself over the head for creating unnecessary variables for x and y.

Thank you very much. :slight_smile: I love how helpful this community is.