- Home /
Strange behaviour when switching camera
Hi all,
I was wondering if anyone could offer some insight into this issue I'm having when switching cameras.
The code looks like this:
public Camera Camera1;
public Camera Camera2;
float theTime;
void Start () {
Camera1 = GetComponent<Camera> ();
Camera2 = GetComponent<Camera> ();
}
void Update () {
theTime = Time.time;
if (theTime > 6) {
Camera1.enabled = true;
Camera2.enabled = false;
}
Debug.Log ("Camera1 value: " + Camera1.enabled);
Debug.Log ("Camera2 value: " + Camera2.enabled);
}
So the idea is whenever theTime value is greater than 6, we change the camera view from Camera1 to Camera2.
The first issue is that it only works when Camera1.enable is set to true and Camera2.enable is set to false. I don't understand why this works?! Surely it makes sense for Camera1.enable to be set to false since we're 'disabling' the view, and then for Camera2.enable to be set to true to 'activate' the view.
The second issue is that when I alter the value of Camera1.enable and Camera2.enable in the if statement, both values change to false when only one should change. Does anyone know why this happens?
Hope someone can help clear this up!
Answer by kevindang · Apr 06, 2017 at 01:43 PM
Oh, got it. I had to remove this from void Start():
Camera1 = GetComponent<Camera> ();
Camera2 = GetComponent<Camera> ();
Have I been interpreting the use of GetComponent incorrectly then? I thought whenever you declared a public object, you always had to do GetComponent to retrieve it. Is this an incorrect use of GetComponent?
The way I always get components is either of these two:
Camera1 = gameObject.GetComponent();
or
Camera1 = gameObject.GetComponent(typeof(Camera)) as Camera;
Your answer
![](https://koobas.hobune.stream/wayback/20220612114834im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Full screen camera missing? 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why are my 2D sprite GameObjects blinking and how do I fix this problem? 0 Answers