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