相机切换机制



作为我研究项目的一部分,我一直在测试相机切换机制。

到目前为止,我已经能够注意到以下代码的两件事。在我应用此代码之前,默认情况下显示主摄像头。但是,现在默认情况下显示最后一个相机,即使我禁用脚本,我也不确定如何解决此问题。此外,下面的代码在相机[当前相机索引 - 1]的第 46 行抛出一个 ArrayIndexOutofRangeException.enable = false;在 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");
        }
    }
}
}

代码没有问题,刚刚在 Unity 中检查过。但我建议您在媒体上检查相机是否有任何值

if (Input.GetKeyDown(KeyCode.C))
{
    if (cameras.Length > 0)
    {
        DoStuff();
    }
}

相关内容

  • 没有找到相关文章

最新更新