如何在层次结构中的所有摄像机(包括禁用的摄像机)之间切换?

时间:2019-11-16 23:33:03

标签: c# unity3d

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;
    [HideInInspector]
    public Vector3 currentCameraOriginalPosition, currentCameraPosition;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;

    private int currentCamera = 0;

    void Start()
    {
        cameras = Camera.allCameras;
        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            Debug.LogError("Need more then 1 camera for switching..");
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
        currentCameraOriginalPosition = originalPosition[0];
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera].enabled = true;
            currentCameraName = cameras[currentCamera].name;

            currentCameraOriginalPosition = originalPosition[currentCamera];
        }

        lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
        currentCameraPosition = lastCameraPosition[currentCamera];
    }
}

我认为这是问题所在:

cameras = Camera.allCameras;

allCameras仅返回启用的摄像机。

在运行游戏时,我只有1个摄像头,但我有两个摄像头,其中一个被禁用了:

Main Camera

不确定如何获得此相机以及其他禁用的相机。

例如,在这种情况下,我想在拥有的摄像头和主摄像头之间切换,但是由于禁用了主摄像头,因此无法获取/查找主摄像头,因此我想它也不会获取/查找其他禁用的摄像头。

0 个答案:

没有答案