- Home /
cameras switch doesn't work
Hi Everyone! I'm trying to switch between cameras in unity for my game, but not a usual switch - I want them to get switched when the player is on one terrain or another (thats not the problem, I used the function
void OnTriggerEnter(Collider Other)
and used tags; the problem was to switch the cameras. I tryed to to the next code in this function^^ but it didn't work:
GameObject.Find("Main Camera").GetComponent("Camera").camera.enabled = false;
GameObject.Find("2D Camera").GetComponent("Camera").camera.enabled = true;
then I tryed something else - I used another code -
public Camera[] cams;
and switched the cameras when something heppend, but this time the problem was to put the cameras in the player, and I don't understand what is wrong. can someone help me please?
Answer by Brahim113 · May 11, 2013 at 07:22 PM
Your logic worked for me. I made a fast script in 2min public class PlayWithCameras : MonoBehaviour {
Camera _camera1;
Camera _camera2;
void Start () {
_camera1 = GameObject.FindGameObjectWithTag("Camera1").GetComponent<Camera>();
_camera2 = GameObject.FindGameObjectWithTag("Camera2").GetComponent<Camera>();
}
void Update () {
if(Input.GetKeyDown(KeyCode.T))
{
_camera1.enabled = false;
_camera2.enabled = true;
}
if(Input.GetKeyDown(KeyCode.R))
{
_camera1.enabled = true;
_camera2.enabled = false;
}
}
}
You can improve this. But it works. You could easily do it with a array. But this is how my hierachy looks like ingame
TempCameras (Just a gameObject that has the script) I then created 2 empty gameObjects and put one camrea in each. I tagged them with Camera1 and Camera2. I put these 2 gameobjects as childobjects of the TempCameras object (But you dont have to)
Thats it. Hope this helpes you on your way.
Thanks, You are awesome! its not what I want, even not close actually, because I made something like this - but you fixed one of my codes! my code:
GameObject.Find("$$anonymous$$ain Camera").GetComponent("Camera")...
your code: _camera1 = GameObject.FindGameObjectWithTag("Camera1").GetComponent();
so thank you very much! (but, if someone understood me and know what I want, can you help me too, so it will be easyer to me in the game?)
I'm sorry, I thought it would be good, but the code didn't work for me. can someone else help me?
Converted answer to comment again. Please use the comment button for comments, and the answer button for answers, or you will be downvoted and lose karma.
I have tested my code and it works fine. If you could be more precise in what you are trying to achive. $$anonymous$$aybe i could help you out.