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();


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) 


climbDirection = currentLadder.ClimbDirection();

Anyone can see what's the cause ?


2 Answers 2


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.


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


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .