- Home /
Script to move between camers
I'm trying to set up a script (C#) where when I click on a button it will go to another camera. Presently my knowledge in C# is very limited (call me a noob) so a little assistance as to where I can educate myself or some form of code to help me in the right direction.
Presently I have a camera on each of the objects that are going to be effected (instead of having the camera moving) which is how I want to do it, if that's in-effecient then I'm willing to work another route.
Because of my current knowledge and experience I am unsure where to start, I have looked at the scripting reference and it doesn't make any sense. In advance, thank you for your help.
Answer by aldonaletto · Jun 09, 2012 at 04:30 AM
This will be highly inefficient if all the cameras are enabled; if you keep all cameras disabled and only the current one enabled, there's no problem.
You could place all cameras in an array at the Inspector, and jump sequentially from one to another each time you click some button, like this (attached to any scene object):
using UnityEngine; using System.Collections;
public class SwitchCameras: MonoBehaviour {
public Camera[] cameras; // set the size and drag the cameras here in the Inspector
public int curCamera = 0;
void Start(){
SelCamera(curCamera);
}
void SelCamera(int n){
for (int i = 0; i < cameras.Length; i++){
cameras[i].enabled = (i == n); // enables only the camera index n
}
}
void OnGUI(){
if (GUI.Button(new Rect(10, 10, 100, 40), "Switch camera")){
curCamera = (curCamera + 1)% cameras.Length;
SelCamera(curCamera);
}
}
}
This is very helpful, I have to some tweeking with the script but it is a good start.
Your answer
Follow this Question
Related Questions
RTS Camera movement wrong after rotation 1 Answer
Getting camera to stick to object 1 Answer
Camera Follow Player using a path 0 Answers