【发布时间】:2018-12-27 11:17:40
【问题描述】:
作为我研究项目的一部分,我一直在测试相机切换机制。
到目前为止,我可以通过下面的代码注意到两件事。在我应用此代码之前,默认情况下会显示主摄像头。但是,现在默认显示最后一个摄像头,即使我禁用了脚本,我也不确定如何解决这个问题。此外,下面的代码在 camera[currentCameraIndex - 1].enabled = false; 的第 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");
}
}
}
}
【问题讨论】:
-
currentCameraIndex除了这两种方法可以在其他地方修改吗? -
你是在运行时修改
cameras数组还是在其他代码的某个地方修改? -
您的主摄像头是该阵列中的第一个摄像头吗?您还应该在更新中添加一个 if 检查,以确保您的相机阵列至少为 1 个或更多。如果您有一个大小为 0 的相机阵列,则 cameraIndex 0 超出范围。如果您可以向我们展示具有此脚本的检查,并确保它是您的场景中此脚本的唯一实例,将会更有帮助。
-
@ikerbera 我不这么认为,因为这是文件中仅有的两种方法。
-
@trollingchar no.
标签: c# unity3d graphics camera indexoutofrangeexception