Hi guys, first time poster. I’m very new to both Unity and C# so forgive me if what I’m asking is very basic or if I’m missing something very obvious but I simply cannot understand why the two codes below work differently from one another. I’m currently doing the Unity Learn Essentials Pathway and one of the final missions is to implement something original and unique to the final scene. I came up with the idea of implementing an “On/Off” button for the vacuum cleaner and later adding a unique sound for each switch.
The first code I wrote to implement my idea was as follows (Only typing the relevant parts):
bool power = false; // Starting the vacuum cleaner in “Off” mode
void Update()
{
// If vacuum cleaner is turned on, then turn it off after pressing the “O” button.
if (power == true && Input.GetKeyDown(KeyCode.O))
{
power = false;
}
// If vacuum cleaner is turned off, then turn it on after pressing the “O” button.
if (power == false && Input.GetKeyDown(KeyCode.O))
{
power = true;
}
}
Implementing the above code produces a strange outcome. The code only allows me to turn the vacuum cleaner on but doesn’t let me turn it off. If I start the vacuum cleaner in off mode (i.e. power = false) then I can turn it on in the game by pressing “O” but I can’t turn it off again, and if I start the vacuum cleaner in on mode (i.e. power = true) then it permanently stays on and never responds to me pressing “O” to turn it off. I played around with the code and realized that I could make it work the way I wanted by rewriting the code as follows:
bool power = false; // Starting the vacuum cleaner in “Off” mode
void Update()
{
// If the “O” button is pressed, check to see whether power is “On” or “Off”, then switch power.
if (Input.GetKeyDown(KeyCode.O))
{
if (power == true)
{
power = false;
}
else
{
power = true;
}
}
}
This second block of code works exactly the way I want. I can now turn the vacuum cleaner both on and off anytime by pressing “O”. What I don’t understand is that why does the first block of code not work and the second one works? What is happening in the first block that is preventing me from switching power to false by pressing “O”?