Object reference not set to instance of an object

Okay, I’m using the code:

if (gameObject.Find("First Person Controller").GetComponent("CharacterMotor").grounded == false)
{

}

I copied and pasted this code from an earlier working script. I’m 100% positive that the game object First Person Controller is there, and the component I’m trying to get is there. I also know the variable is correct, but I still get the error when I try to run the game saying “NullReferenceException: Object reference not set to an instance of an object”. I have tried making a variable for it and putting the first person controller in it, then calling it from there, but I got the same error. Do you guys have any idea why I am getting this error? Thanks

The tough part about programming is that sometimes, our 100% certainty doesn’t amount to 100% of the truth. :wink:

If I were you, I’d build up that line of code with gradual Debug.Logs to see if the calls to GameObject.Find and GetComponent actually do return what you’re 100% positive they do.

You shouldn’t use Find if that’s inside Update, my tip is to first off variable “First Person Controller” (var fpc : Transform). Also later variable the whole fpc.GetComponent(CharacterController) in Start () as so:

cController = fpc.GetComponent(CharacterController);

If it’s an if (“boolean”) you can also instead negate with:

if (!fpc.cController.grounded)

The first steps will give you a real performance boost.

var fpc : Transform;
var cController;
function Start () {
    cController = fpc.GetComponent(CharacterController);
}
function Update () {
    if (!fpc.cController.grounded) {
        //Character is jumping/falling
    }
}

Hopefully this might also solve your issue. Most of the times when this happens it’s because the variable you’re trying to reach inside an object or the name of the object is called or spelled differently (I’m not familiar with the CharacterController class). I think that grounded is reached from the actual CharacterController instead of CharacterMotor though.