2
\$\begingroup\$

I'm making a script to climb ladders in my game. These are the variables used in the function.

private Vector3 climbDirection = Vector3.zero;
private Ladder currentLadder = null;
private bool latchedToLadder = false;

And here is the function

void LatchLadder (GameObject latchedLadder, Collider collisionWaypoint){
    currentLadder = latchedLadder.GetComponent<Ladder>();
    latchedToLadder = true;
    climbDirection = currentLadder.ClimbDirection();
    gameObject.SendMessage("OnLadder",null,SendMessageOptions.RequireReceiver);

}

Everytime I collide with the ladder in playmode i get

NullReferenceException: Object reference not set to an instance of an object
UseLadder.LatchLadder (UnityEngine.GameObject latchedLadder, UnityEngine.Collider collisionWaypoint) 
UseLadder.OnTriggerEnter (UnityEngine.Collider other) 

at

climbDirection = currentLadder.ClimbDirection();

Anyone can see what's the cause ?

\$\endgroup\$
3
\$\begingroup\$

The object you're colliding with does not have the Ladder component. If you try to get a component from an object that doesn't have it, GetComponent will return null. You should check to make the sure component isn't null before doing anything with it, but you should probably make sure the object you're trying to latch on to is a ladder in the first place. You can do that by checking to see if it has the ladder component.

Before you call LatchLadder, perform a check similar to:

//inside your collide function
if(collidedGameObject.GetComponent<Ladder>() != null) {
    //it has the ladder component, it's a ladder
    LatchLadder(collidedGameObject, collisionWaypoint);
} else {
    //we've collided with something that isn't a ladder, do something else.

}
\$\endgroup\$
1
\$\begingroup\$

Most likely latchedLadder has no Ladder component, in which case latchedLadder.GetComponent<Ladder>(); returns null;

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.