作为研究项目的一部分,我一直在测试相机切换机制。
到目前为止,使用以下代码我已经注意到了两件事。在应用此代码之前,默认情况下显示了主摄像机。但是,现在默认情况下显示的是最后一台摄像机,即使我禁用了该脚本,也不确定如何解决此问题。另外,下面的代码在camera [currentCameraIndex-1]中的第46行抛出ArrayIndexOutofRangeException。在else子句中。
你们中的任何人都可能知道发生了什么事以及我该如何解决吗?
非常感谢您!
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
public Camera[] cameras;
private int currentCameraIndex;
// Use this for initialization
void Start()
{
currentCameraIndex = 0;
//Turn all cameras off, except the first default one
for (int i = 1; i < cameras.Length; i++)
{
cameras[i].enabled = false;
}
//If any cameras were added to the controller, enable the first one
if (cameras.Length > 0)
{
cameras[0].enabled = true;
Debug.Log("Camera with name: " + cameras[0].name + ", is now enabled");
}
}
// Update is called once per frame
void Update()
{
//If the c button is pressed, switch to the next camera
//Set the camera at the current index to inactive, and set the next one in the array to active
//When we reach the end of the camera array, move back to the beginning or the array.
if (Input.GetKeyDown(KeyCode.C))
{
currentCameraIndex++;
Debug.Log("C button has been pressed. Switching to the next camera");
if (currentCameraIndex < cameras.Length)
{
cameras[currentCameraIndex - 1].enabled = false;
cameras[currentCameraIndex].enabled = true;
Debug.Log("Camera with name: " + cameras[currentCameraIndex].name + ", is now enabled");
}
else
{
cameras[currentCameraIndex - 1].enabled = false;
currentCameraIndex = 0;
cameras[currentCameraIndex].enabled = true;
Debug.Log("Camera with name: " + cameras[currentCameraIndex].name + ", is now enabled");
}
}
}
}
答案 0 :(得分:0)
代码没有问题,已统一检查。但是我建议您在印刷机上检查相机是否有任何值
if (Input.GetKeyDown(KeyCode.C))
{
if (cameras.Length > 0)
{
DoStuff();
}
}