Switching between cameras (2555)

Hi, I would like to switch between cameras depending on the position of my player position, how can I do this please?

Thanks a lot for your time.

4 Answers

4

You can activate and deactivate cameras if you can get a hold of the object that holds them.

//cameraObject is the gameObject which holds the camera

cameraObject.camera.active = false;

So If you had a script which kept track of all the cameras in your scene then you could switch cameras easily. For example here is a function which would go through an array of camera objects and turn a certain one on (based on the index sent to it).

var cameras : GameObject[]; 

function SelectCamera (index : int) {
for (var i : int=0 ;i<wcameras.length; i++) {
    // Activate the selected camera
    if (i == index){
        cameras*.camera.active = true;*
 *// Deactivate all other cameras*
 *}else{*
 _cameras*.camera.active = false;*_
 _*}*_
_*}*_
_*```*_
_*<p>You could use this function by calling it with a message</p>*_
_*```*_
_*BroadcastMessage ("SelectCamera", 1);*_
_*```*_
_*<p>or by outright calling it</p>*_
_*```*_
_*SelectCamera(1);*_
_*```*_
_*<p>You just need to get hold of the instance of the script it's in</p>*_

DastardlyBanana's answer would be more flexible, but i'll post my (very simple!) answer here anyway:

You could check for a collision with a collider and then enabled/disable your cameras, so:

var Camera1 : Camera;
var Camera2 : Camera;

function Start(){
    Camera1.enabled = true;
    Camera2.enabled = false;

}

function OnTriggerEnter (other : Collider) {

    if(other.gameObject.name == "switch_camera"){

        Camera1.enabled = false;
        Camera2.enabled = true;

    }
}

function OnTriggerExit (other : Collider) {

    if(other.gameObject.name == "switch_camera"){

        Camera1.enabled = true;
        Camera2.enabled = false;

    }
}

Camera1 and Camera2 are assigned in the editor, or you could assign them with code.

Cheers.

Thanks because I've just looked at your answer I had a lot o thngs to do but it's not as interresting as your answer thanks to you 2!!

Keep comments off of the answers area

This script worked for me. It only works for 2 camera’s as far as I know but you might be able to edit it.

var cam1 : Camera;
var cam2 : Camera;

function Start() {
cam1.enabled = true;
cam2.enabled = false;
}

function Update() {

if (Input.GetKeyDown(KeyCode.C)) {
    cam1.enabled = !cam1.enabled;
    cam2.enabled = !cam2.enabled;
}

}