quick question, new to Godot - I have a variable which can be 0 or 1 what's the best way to flip it from 0 to 1 and vice versa?

I tried

variable = !variable

but that causes the value to be either true or false and breaks when I use it in an array

eg. my_array[variable]

You can also do this:

int(!num)

Is it an int or a float?

If it's an int:

x = 0 if x == 1 else 0

x = (x + 1) % 2

if variable == 1:
    variable = 0
if variable == 0:
	variable = 1

I don't know if they were serious, but those last two examples aren't correct.

I was implying they might want to use booleans and bitwise operators.

var this: bool = false
this = ~this#might only work for comparisons tho

so alternatively

this = !this

I noticed Nerdz forgot elseif or else. The variable would be changed twice and end up what it was if it was 1.

@fire7side said: I noticed Nerdz forgot elseif or else. The variable would be changed twice and end up what it was if it was 1.

elif variable == 0:
   Variable = 1

thanks guys - newbie learning Godot - appreciate your help

having a lot of fun with it

match x:
	0: x = 1
	1: x = 0

I tested this because I wasn't sure if it would do both like 2 if's, but it doesn't.

@Megalomaniak bitwise should work and would be the least code and I imagine the fastest.

@Martoon said: variable = 1 - variable

This is the cleanest way

@RichNaoo said:

@Martoon said: variable = 1 - variable

This is the cleanest way That switches 1 to -1 and back. Not that you can't use -1, depending on if you actually need 0.

@Nerdzmasterz said:

@RichNaoo said:

@Martoon said: variable = 1 - variable

This is the cleanest way That switches 1 to -1 and back. Not that you can't use -1, depending on if you actually need 0.

It doesn't: 1-1=0 and 1-0=1

@cybereality said: @Megalomaniak bitwise should work and would be the least code and I imagine the fastest.

Bitwise could be done using Xor: variable = 1 (effectively flipping just bit 0)

But binary Not won't work, because it flips all bits. ~0 is -1 ~1 is -2