What is wrong with my script?

Notes:

  • Unity Version: 5.4.0f3 (64-Bit)

I tried to create a simple script to toggle between two cameras (A first and a third person) and when I did, Unity gave me some errors. What is wrong with my script?

Script:

#pragma strict

public var ThirdPersonCamera: GameObject;
public var FirstPersonCamera: GameObject;

function Start () {
	FirstPersonCamera.SetActive(true);
}

function Update () {
	if (Input.GetButtonDown("Perspective Toggle")) {
		if (ThirdPersonCamera.SetActive(false)) {
	   	   FirstPersonCamera.SetActive(true);
		else
	   	   FirstPersonCamera.SetActive(false);
	    }
    }
}

Errors:

  • BCE0044: expecting }, found ‘else’.
  • BCE0044: expecting EOF, found ‘}’.
  • BCE0044: expecting ‘*’, found ‘’.

I then went on to try a more manual approach, however, this didn’t work either.

Script:

function Update () {
	if (Input.GetButtonDown("Perspective Toggle")) {
		if (ThirdPersonCamera.SetActive(false)) {
		   FirstPersonCamera.SetActive(true);
	    }
	    if (ThirdPersonCamera.SetActive(true)) {
	       FirstPersonCamera.SetActive(false);
	    }
    }
}

Errors:

  • ‘void’ cannot be used in a boolean context.

I would be very grateful if somone could tell me what I am doing wrong and provide a working version of the script. :slight_smile: Many thanks.

In the first version two braces are missing. For both versions it’s wrong to have SetActive() in the if() clause. To check the status use “activeSelf” or “activeInHierarchy”. These are variables of GameObject, not methods.

if ( FirstPersonCamera.activeSelf )
{
  FirstPersonCamera.SetActive( false );
  ThirdPersonCamera.SetActive( true );
}
else
{
  ThirdPersonCamera.SetActive( false );
  FirstPersonCamera.SetActive( true );
}

Untested, but you should get the idea.