GetComponent, set boolean to true but it willn't revert

Hi, having a trouble. I’m trying it with easier way or even harder way but it’s not working lel.

This code I’m having:

if(Input.GetButtonDown("Interaction")) {
    if(ladder.GetComponent<Ladder>().isClimbing) ladder.GetComponent<Ladder>().isClimbing = false;
    if(!ladder.GetComponent<Ladder>().isClimbing) ladder.GetComponent<Ladder>().isClimbing = true;
}

When I will touch button first, it will activate checkbox, change boolean to true but when I will trigger it again. It willn’t set to false.
Any idea?

3 Answers

3

This is basically two if statements one after the other. Both will execute, which means the first one makes sure isClimbing is always set to false and the second one is always true.
Try something like

ladder.GetComponent().isClimbing = !ladder.GetComponent().isClimbing,

or

if(ladder.GetComponent().isClimbing)
  ladder.GetComponent().isClimbing = false;
else
  ladder.GetComponent().isClimbing = true;

if you want to learn how if/else statements work.

Yeah I'm idiot :D I'm having these troubles always. I was about to use if/else.. Nevermind, your code is better and smaller so I will use yours. Thanks you for the tip!

Look through your code. You don’t do one line or the other, you do them both.
So, if when you press the “Interaction” button isClimbing is true then the first line executes and sets it to false. The second line then executes and sets it straight back to true again.

You are simply doing both conditions that’s why this is not working but here is a simplified code :

if(Input.GetButtonDown("Interaction"))
{
    ladder.GetComponent<Ladder>().isClimbing = !ladder.GetComponent<Ladder>().isClimbing;
}

or

if (ladder.GetComponent().isClimbing)
{
    ladder.GetComponent().isClimbing = false;
}
else
{
    ladder.GetComponent().isClimbing = true;
}

Yeah, I'm using the code on the top from now, thanks you for the tip.