What is the best way to have a variable toggle between true
and false
? An obvious way is to initialize a variable foo
:
foo = false
and do:
foo = foo.!
every time when I want to toggle. But this becomes verbose when the variable name is long. Is there a simpler way to do this (by using anything such as syntax sugar, original classes)? Especially, I wonder if there is a way to toggle by just giving it a single method:
foo.some_method
The NOT operator is used before the variable to be toggled and the result is assigned to the same variable. This will effectively toggle the boolean value.
Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.
In this lesson, I teach you the easiest way to flip or toggle a bool variable in C# for Unity. This is done by having your destination variable followed by the equals operator and the exclamation operator in front of the source variable and in this case the destination and the source should be the same variable.
You can use XOR operator.
foo ^= true
foo = false
foo ^= true # => true
foo ^= true # => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With