public Camera camera1; public Camera camera2; // Use this for initialization void Start () { camera1 = (Camera)(object)GameObject.FindGameObjectWithTag("MainCamera"); camera2 = GetComponent<Camera>(); camera1.enabled = true; camera2.enabled = false; void Update () { if (Input.GetKey(KeyCode.W)) { camera2.enabled = !camera2.enabled; camera1.enabled = !camera1.enabled; transform.Translate(Vector3.forward * Time.deltaTime * speed); }; 

When you run, unity gives this error -

InvalidCastException: Cannot cast from source to destination type. CubeScript.Start () (at Assets / scripts / CubeScript.cs: 12) - That is, it swears per line

 camera1 = (Camera)(object)GameObject.FindGameObjectWithTag("MainCamera"); 

- because of the type of ghosts, but in another way I cannot convert from GameObject to Camera - because I need to assign one concrete one from two cameras on the scene to this field, and this is how I understand the only way to get the link to the external one an object?

And then when you press the corresponding W key, an error occurs:

nassignedReferenceException: The variable camera2 of CubeScript has not been assigned. You can use the script in the inspector. CubeScript.Update () (at Assets / scripts / CubeScript.cs: 23) - why does unity say that the value for the variable camera2 is not assigned? After all, here -

 camera2 = GetComponent<Camera>(); 

I assign it a value - the object gets the camera that I “hung” on the object, and

camera1 = (Camera)(object)GameObject.FindGameObjectWithTag("MainCamera");

the studio gets a "main camera" - that is, I have two cameras in my scene

    1 answer 1

    Your whole problem lies in the line where you are looking for the MainCamera object:

    camera1 = (Camera)(object)GameObject.FindGameObjectWithTag("MainCamera");

    First, GameObject.FindGameObjectWithTag returns the type GameObject[] , that is, an array that you can never convert to Camera , you can read about it in the documentation . You can correct this if the result (array) is checked for the number of elements, that is, in your case there should be 1 element and refer to it, that is, something like this:

     var goArray = GameObject.FindGameObjectWithTag("MainCamera"); var cameraGO = goArray[0]; 

    and then get the camera itself on this object, not by means of type casting, but via GetComponent<Camera>()

    Secondly, you can use the GameObject.FindWithTag method, which will be much easier in your case, since it will return 1 active GameObject with the specified tag. But he will still need to call GetComponent<Camera>() . No type conversion is needed.

    Also if

    camera2 = GetComponent<Camera>();

    gives an error, it can be only if there is no Camera component on the GameObject to which your script is attached.