Chaost
Chaost

Reputation: 147

C# toggle boolean within a loop / Unity toggle boolean in Update()

The title may look inconclusive, but it's the same thing, it's just explained differently when talking about the Unity engine, just in case any Unity vets are to see my post.

In the Unity engine, there are certain methods that do specific tasks within a class, one of these is the Update() method, which loops for every frame (hence the loop expression in the title).

The idea is that I will have an expression inside this loop, waiting for the user to click a key, which would in turn toggle a boolean variable. I've tried to implement this in a number of different ways, but the way I'm doing it now seems the most promising.

if (Input.GetKeyDown(KeyCode.Delete))
{
    if (this.modGodspeed)
    {
        this.speedMult = 1f;
        this.godSpeedToggled = "OFF";
        this.modGodspeed = false;
    }
    if (!this.modGodspeed)
    {
        this.speedMult = 5f;
        this.godSpeedToggled = "ON";
        this.modGodspeed = true;
    }
}

During the startup the boolean is initialized to false, so it says OFF by default, and when I click the delete key the first part of this works, and it shows ON and the speedMult variable is set to 5. The problem is that it does not toggle off again. Clicking 'delete' again does nothing.

Code description:

Input.GetKeyDown(Keycode.Delete) = Part of the Unity library, reads key input.

modGodSpeed = Boolean I'm talking about.

speedMult = Speedmultiplier to be toggled.

godSpeedToggled = String variable, shows the user whether godspeed is toggled or not.

Upvotes: 1

Views: 1365

Answers (1)

Programmer
Programmer

Reputation: 125245

Your code is doing exactly what you wrote.

This is what is happening:

1.if (this.modGodspeed) will execute and set modGodspeed to false.

2. if (!this.modGodspeed) below it will execute in the-same frame and set modGodspeed to true.

3.This will repeat when you press the delete key (KeyCode.Delete) again.


#2 shouldn't execute if the first if statement executes. You need to make the if statement to check only once so that if the modGodspeed variable is true, the other if statement below it won't be checked again. This is why there is an if, else if and else statements.

Use else if in your second if statement:

if (this.modGodspeed)
{
    ....
}
else if (!this.modGodspeed)
{
    ...
}

Or simply use the else statement since the modGodspeed variable is a boolean variable which can either be true or false.

if (this.modGodspeed)
{
    ....
}
else
{
    ....
}

Upvotes: 3

Related Questions