- Home /
Switching camera's error
Hi,
I have a first person controller with a "Main Camera" and I have a second camera somewhere else on the scene named "Puzzle Camera".
When I hit play, I immediately see from the "Puzzle Camera" view, but I should start at the Main Camera instead. To do this, I use this code:
function Start (){
GameObject.Find("Puzzle Camera").active = false;
}
When I use that script I no longer start seeing from that camera. Now, I also placed a box somewhere which works with an OnTriggerEnter function. Once I hit that box, I want to view from the Puzzle Camera and not the Main Camera and once the puzzle is solved, I want to switch back to the Main Camera.
I used this:
function OnTriggerEnter (player : Collider) {
if (player.gameObject.tag == "Player") {
if(triesLeft == true) {
//Switch to puzzle camera
GameObject.Find("Puzzle Camera").GetComponent("Camera").active = true;
GameObject.Find("Main Camera").GetComponent("Camera").active = false;
}
}
}
Once I hit the box I get a "NullReferenceException" error. How do I solve this? I am using Unity 4.
Answer by Nidre · Dec 14, 2012 at 02:02 PM
Find method cannot find disabled objects.Your GameObject.Find("Puzzle Camera").GetComponent("Camera").active = true; line returns null becasue of that.
You can save a referance to the Puzzle Camera before deactivating it on the start Method. Or you can find your camera by using Camera.allCameras[indexOfYourCamera]; (Cameras are usually ordered by their depth value)
Thank you for the info! Is there also a way for me to disable/enable a camera by name without the find method? I used: "Camera.allCameras[10].active = false;" (the cam depth is set to 10) and I get an error: IndexOutOfRangeException: Array index is out of range).
As i said you can use Camera.allCameras[indexOfYourCamera] to acces all the cameras in your scenes wheter they are active or not.
No problem at all.(a little up vote or accepting my answer would be nice for some karma tho:))
Ah you got me wrong.
allCameras is an array. So if you have 2 Cameras,Lets say Camera1 is depth 10 and Camera2 have depth 5 the array should cointain the following.
{Camera2,Camera1}
And if you wanted call the Camera2 you should have wrote "Camera.allCameras[0]" and for Camera1 this "Camera.allCameras[1]"
Btw im not certainly sure about this order works by depth value.It's just something i have experinced a couple times.