如果按某个键,如何在相机之间切换?

时间:2016-12-28 19:17:02

标签: unity3d

好的,我在Unity的层次结构中设置了2个摄像头:

enter image description here

我想知道,在游戏中,当按下某个键时,如何在两个摄像头之间切换?我知道我可能需要为此制作一个脚本,只是不确定我该怎么做。

2 个答案:

答案 0 :(得分:1)

非常基本的问题,你应该去一些c#教程。

无论如何,这样做。把它放在Update方法中:

if (Input.GetKeyDown("space"))
    {
        //don't forget to set one as active either in the Start() method
        //or deactivate 1 camera in the Editor before playing
        if (Camera1.active == true)
        {
            Camera1.SetActive(false);
            Camera2.SetActive(true);
        }

        else
        {
            Camera1.SetActive(true);
            Camera2.SetActive(false);
        }
    }

答案 1 :(得分:1)

您可以添加多个摄像头

  using UnityEngine;

using System.Collections;

public class CameraController : MonoBehaviour {

// Use this for initialization
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].gameObject.SetActive(false);
    }

    //If any cameras were added to the controller, enable the first one
    if (cameras.Length>0)
    {
        cameras [0].gameObject.SetActive (true);
        Debug.Log ("Camera with name: " + cameras [0].GetComponent<Camera>().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.


}

public void Change()
{
        currentCameraIndex ++;
        Debug.Log ("C button has been pressed. Switching to the next camera");
        if (currentCameraIndex < cameras.Length)
        {
            cameras[currentCameraIndex-1].gameObject.SetActive(false);
            cameras[currentCameraIndex].gameObject.SetActive(true);
            Debug.Log ("Camera with name: " + cameras [currentCameraIndex].GetComponent<Camera>().name + ", is now enabled");
        }
        else
        {
            cameras[currentCameraIndex-1].gameObject.SetActive(false);
            currentCameraIndex = 0;
            cameras[currentCameraIndex].gameObject.SetActive(true);
            Debug.Log ("Camera with name: " + cameras [currentCameraIndex].GetComponent<Camera>().name + ", is now enabled");
        }
    }

}