![unity3d Runtime 切换摄像机 - 重庆unity3d - unity3d工作室](http://img1.ph.126.net/Po_eV4nVc5Hwcx-wrNy3Rg==/6597162125633625811.jpg)
为了实现相机的切换,你只需要禁用一个、启用另一个。本教材中我创建了一个简单的场景:一个 cube、3 个相机。为了遍历这些摄
像机,我们可以使用 tag 标记来实现。选取摄像机对象,放入一个列表中,然后使用 for 循环遍历,找到 camera 组件,然后禁用所有
的。最后启用指定的摄像机。
Javascript
function Update () {
if(Input.GetKey("1")){
Debug.Log("Using Camera One");
camSwap(1);
}
if(Input.GetKey("2")){
Debug.Log("Using Camera Two");
camSwap(2);
}
if(Input.GetKey("3")){
Debug.Log("Using Camera Three");
camSwap(3);
}
}
function camSwap(currentCam : int){
var cameras = GameObject.Fi ndGameObjectsWithTag("cam");
for (var cams : GameObject in cameras){
cams.GetComponent(Camera).enabled = false;
}
var oneToUse : String = "Camera"+currentCam;
gameObject.Find(oneToUse).GetC omponent(Camera).enabled = true;
}
C# Equivalent
using UnityEngine;
using System.Collections;
public class camControl : MonoBehaviour {
void Update () {
if(Input.GetKey("1")){
Debug.Log("Using Camera One");
camSwap(1);
}
if(Input.GetKey("2")){
Debug.Log("Using Camera Two");
camSwap(2);
}
if(Input.GetKey("3")){
Debug.Log("Using Camera Three");
camSwap(3);
}
}
void camSwap(int currentCam){
GameObject[] cameras = GameObj ect.FindGameObjectsWithTag("cam ");
foreach (GameObject cams in cameras){
Camera theCam = cams.GetC omponent<Camera>() as Camera;
theCam.enabled = false;
}
string oneToUse = "Camera"+currentCam;
Camera usedCam = GameObject.F ind(oneToUse).GetComponent<Camer a>() as Camera;
usedCam.enabled = true;
}
}