I saw and read about three related topics but none had a answer to my problem.
The thing is, I’m creating a ladder script for a 2D side scrolling game and the idea is disable the gravity and the “x” movement when the player press “up” nead the ladder to climb it. The problem is that I need a collider on the upper part so the player can walk on the upper floor without falling. I pointed that upper part on the following image:
So the idea is to disable the collider when I’m climbing the ladder and enable it when I’m not.
And that collider is on the ladder’s script, so I created a variable of type of the LadderScript on the player’s script to receive the reference of the ladder that the player is about to climb when the player enters the trigger area:
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.layer == 14) {
isInsideLadderArea = true; //this works
lastLadderPosition = new Vector3(collision.transform.position.x, collision.transform.position.y); //this works
lastLadder = collision.gameObject.GetComponent<LadderScript>(); // this returns null (why???)
print(collision.gameObject.layer); //for debug purposes, prints exactly the layer that the object it's on
}
}
private void DropFromLadder() {
isClimbingLadder = false;
rb2d.gravityScale = 4;
lastLadder.EnableCollider(); //this get me an error because of of null reference
}
private void ClimbLadder() {
isClimbingLadder = true;
rb2d.gravityScale = 0;
lastLadder.DisableCollider(); //this get me an error because of of null reference
}
Then when the OnTriggerEnter2D is activated, I get a vector 3 position of the object, a change on my bool value, I can even print the layer that my object is on, but some reason that completely eludes me, I can’t set the reference of the ladder object on my variable.
On execution time, I forcedly dragged my ladder object into the “lastLadder” field and it works fine, but if exit the trigger area, as soon as enter the trigger area again, my lastLadder gets a null value again.
I tried everything, including static variables, methods with parameters but got nothing, so I’d be very, very grateful if anyone can help me.
This the ladder script:
public class LadderScript : MonoBehaviour {
public Collider2D ladderUpperGround;
void Start () {
ladderUpperGround.enabled = true;
}
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.layer == 15) {
print("player entered"); //not activating
}
}
public void EnableCollider() {
ladderUpperGround.enabled = true;
}
public void DisableCollider() {
ladderUpperGround.enabled = false;
}
}