Understanding C#: toggle/switch camera function

Hey all,

I played with the following script to use a key in order to change the camera view between the main camera and a secondary camera (like first person and third person views). I achieve it with that script and all works as it should:

public cam1 : Camera;
public cam2 : Camera;
public KeyCode CameraKey;

function Start() {
     cam1.enabled = true;
     cam2.enabled = false;
}
function Update() {
     if (Input.GetKeyDown(CameraKey)) {
         cam1.enabled = !cam1.enabled;
         cam2.enabled = !cam2.enabled;
     }
}

BUT I would love to understand what this “xxx.enabled = !xxx.enabled;” does. How to understand this kind of function. Sadly I don’t know what keyword to google here, when you try to google “! =” in combination with “C#” nothing useful comes up…

So my question is how does this logically work? Is there a name for this kind of “toggle-function”?

Thanks in advance :slight_smile:

bool a = true;

// a wordy toggle of a:
if (a == true)
{
  a = false;
} else if (a == false)
{
  a = true;
}

// simpler..
if (a)
{
  a = false;
} else {
  a = true;
}

// and simpler yet..
a = !a;

Edit: the exclamation before a boolean value means “not”, such as “!=” means “not equal to”

Edit: so if a is true, and you say !a, that’s the same as saying false… and if a is false, and you say !a, that’s the same as saying true.

1 Like

Thanks, since I am really a beginner is there some name for that function so I can learn more about that. I still not understand how to really comprehend that.

1 Like
1 Like

Thanks!

1 Like