- Home /
Solved
A bool is equal to the opposite of itself dosen't work
if (Input.GetButtonDown("Look"))
{
look = !look;
}
It doesn't work. I have tried
if (Input.GetButtonDown("Look"))
{
look = true;
}
This works.. Anyone know why?
Why wouldn't it work? It should switch between true/false eachtime u press button.
I have tried, too, and it does work.
What is required, now, is to detail how you came to the conclusion you did, and compare that to other methods for deter$$anonymous$$ing this (I detail $$anonymous$$e below), to see what you've observed different behavior.
Using Visual Studio 2017, the following was tested using the debugger:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class bcheck
{
public bool b = false;
public void check()
{
int n = 100;
while( n > 0 )
{
b = !b;
--n;
}
}
}
class Program
{
static void $$anonymous$$ain(string[] args)
{
bcheck bc = new bcheck();
bc.check();
}
}
}
This code uses a VS 'starting' console application to run a test. Within the loop the debugger was used to step through the code one line at a time, and the value of b was toggled between true and false (and back to true and the again to false) on every occasion exactly as expected.
It would probably be useful to have the rest of your code. Personally I would use "look ^= true" to flip a boolean to it's opposite state, but that may give you the same results depending on what is happening.
its pry not the bool asignment its pry something with your button. try this to confirm:
if (Input.GetButtonDown("Look"))
{ print("if you dont see this in the console your click is not working");
look = !look;
}
Answer by JDelekto · Sep 03, 2018 at 09:25 AM
This code does indeed work; however, it may not work as you intended.
You first example flips the boolean value each and every time the Input.GetButtonDown("Look") returns true.
So, if look is initially false, the first time the button is pressed and released it will become true, the second time it is pressed and released it will become false, etc. and will continue to toggle back and forth between true and false with each subsequent button press.
If you expect the value to stay and remain true, then you need to do what you have done in your second example.
According to the Unity APIs, it should works just in one frame. I press the button, and it changes once. Actually what I want is to flips the boolean value each and every time, but it doesn't work. It stills remains what it was at the beginning.
Add Debug.Log("look bool is flipped to " + look); At least, you will check if your code ever tun and how many times.