- Home /
how to switch camera
im thinking of 2 cameras on my player.. the main camera and the camera itself. then the main camera is of course on the head, facing front. and the other camera is right at the top, facing the top view of the player.
how to switch camera when the player dies.. does it requires to be in script? if it requires a script, where do i put the script?
FYI the simple answer is:
DISABLE ONE CA$$anonymous$$ERA, ENABLE THE OTHER CA$$anonymous$$ERA.
That's how you swap cameras in Unity.
Answer by save · Dec 29, 2012 at 01:34 PM
Yes you would need a script to switch between cameras. The most convenient way of using a switch is to keep the objects you're switching between in an array. This also makes it easier if you want to be able to switch cameras at any point. This example switches when the player presses C and a quick example of how to use it on death and respawn:
#pragma strict
var cameras : Camera[]; //Assign your cameras here in Inspector
private var audioListeners : AudioListener[];
private var currentCamera : int = 0;
function Start () {
audioListeners = new AudioListener[cameras.Length];
for (var i = 0; i<cameras.Length; i++)
audioListeners[i] = cameras[i].GetComponent(AudioListener);
SwitchCamera(0, true);
}
function Update () {
if (Input.GetKeyDown(KeyCode.C)) SwitchCamera(1, false);
}
function SwitchCamera (num : int, direct : boolean) {
if (direct) currentCamera = num; else currentCamera=(currentCamera+num)%cameras.Length;
for (var i = 0; i<cameras.Length; i++) {
cameras[i].enabled = (i==currentCamera);
audioListeners[i].enabled = (i==currentCamera);
}
}
//Death function, for instance called when player's health reaches 0. Switches to camera 2
function OnDeath () {
SwitchCamera(1, true);
}
//Respawn function. Switches to camera 1
function OnRespawn () {
SwitchCamera(0, true);
}
You could remove the toggle switch inside update and instead only use direct switches, if you have more cameras in your scene that should be triggered by certain events.
Answer by Piflik · Dec 29, 2012 at 01:09 PM
You can either use the depth value of a camera to control which one is seen (the camera with the highest depth value will override all others, because it is drawn last), but this will have a detrimental effect on your framerate, because everything will be rendered twice. Only use it if you need both cameras to be active at the same time.
The better option would be to deactivate all cameras except the one you want to use right now. (gameObject.SetActive(false);)
And yes, you would need a script for that. Put a script on the player with references to both cameras, and when he dies, you deactivate one and activate the other. For an even better effect, you could put the second camera to the same position/orientation as the first, and move it up slowly.