Find Closest Camera...Switch to it...

Okay, I'm redoing how my cameras work.

Basically, I have multiple cameras in the environment.

What I want to do is calculate the distance between the player and the cameras (within collider to save time - don't worry about that)

I then want to work out the closest one...

then switch to that camera on buton press... all I really want to know is how to calculate the distance and find the shortest...

thanks in advance.

you should have a list of available cameras first so in start function or in inspector you should populate the elements of an array with all camera objects.

Camera cameras[]; //C# array of cameras

or in js

var cameras : Camera[];

you can use the inspector or just Start/Awake functions when you populated the array then you should write a code like this

function Update ()
if (Input.GetKeyDown ("2"))
for (c in cameras)
if (Vector3.Distance (c.transform.position,transform.position) < mindistance)
mindistance=Vector3.Distance (c.transform.position,transform.position)
activeCamera.enabled = false;
activeCamera = c;
activeCamera.enabled = true;

you should define activeCamera in top of your script as a Camera variable to store the active camera in it. mindistance should be initialized with mathf.infinity at start so you can easily find the nearest camera. for finding all cameras you can create a special tag for them and at runtime use FindGameobjectsWithTag to find them. i don't know if i wrote the js foreach syntax correctly or not. you can use a for statement like this too

for (i=0;i<c.length;i++)

then you should use c *instead of c in your code. what i tried to write in first code block was a statement like C#'s foreach. in C# it should be

* *```* *foreach (Camera c in cameras)* *```*

distance can be found by getting the vector between the camera and the player and using the magnitude function on the vector to get its length. e.g.

var distance = (transform.position - target.transform.position).magnitude;

if you're just comparing lengths then using sqrMagnitude is faster

Thanks for that spinaljack...

I've managed to get it working with this so far...

var camera1 : GameObject;
var camera2 : GameObject;
var other : Transform;

function Update () {

if (Input.GetKey ("2")){

    var dist = Vector3.Distance(other.position, transform.position);

    if (dist <= 500)

        { = false; = true;  

else{ = true; = false; 


So, what I need to do then is to have it looking for multiple cameras. What I'll probably test, is having commendations of working the distance out for each camera, so if it's not under the required distance, it would move onto the next. I know this isn't the most efficient way of doing it though...

but it's a start.