Answer the question
In order to leave comments, you need to log in
Unity3d bug with switching cameras?
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);
};
InvalidCastException: Cannot cast from source type to destination type.
CubeScript.Start() (at Assets/scripts/CubeScript.cs:12)
camera1 = (Camera)(object)GameObject.FindGameObjectWithTag("MainCamera");
- due to type ghosts, but I can’t convert from GameObject to Camera in a different way - because I need to assign one specific camera from two cameras on the stage to this field, and this, as I understand it, is the only way to get a link to an external an object? nassignedReferenceException: The variable camera2 of CubeScript has not been assigned.
You probably need to assign the camera2 variable of the CubeScript script in the inspector.
CubeScript.Update() (at Assets/scripts/CubeScript.cs:23)
camera2 = GetComponent<Camera>();
camera1 = (Camera)(object)GameObject.FindGameObjectWithTag("MainCamera");
- the studio gets the "main camera" - i.e. I have two cameras in the scene
Answer the question
In order to leave comments, you need to log in
You misunderstand the essence of classes and components, carefully read the documentation. GameObject is not a component, you cannot magically get a component from it by casting to another class, for this there is a special method GameObject.GetComponent . Also, in your case, the FindGameObjectWithTag construct can be replaced with a call to Camera.main , the result will be the same. This is not good practice in the context of cameras, but that's up to you. As for the second error, it happens due to the fact that in your start in the first line an exception is thrown, which breaks the method flow, and all subsequent lines are not called, so camera2 remains null.
camera1 = Camera.main
Regarding the second camera
Most likely, there is no such component on the millet object. Just in case, add the attribute RequireComponentr(typeof(Camera)) before the script class. Then remove the script from the object and hang again.
Or assign a camera in the inspector manually
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question