昨天在試着設置多個攝像機之間的切換,結果總是出差錯。
在開始之前提醒幾件事:(很不好意思,自己就傻乎乎地犯了下面的錯誤)
1.這一點是最最重要的,不要將相應的腳本拖拽到Camera上面,要將相應的腳本放到非攝像機的遊戲對象上。(我自己是新建了一個:GameObject->Create Empty)
2.不要偷懶生成了攝像機後不移動位置,結果三個攝像機在相同的位置,切換後看不出效果,還以爲...
3.一定是先關閉所有的攝像機後(除了要使用的那一個),然後激活要用的那個攝像機
4.start()的時候還是要設置一下當前使用的攝像機的(雖然可以使用默認的,但是默認的並沒有關閉其他的攝像機,在遊戲中還可以見到其他相機的模型,當然是自己設置的效果更好的~)
正常的代碼如下:
using UnityEngine;
using System.Collections;
public class CameraControl : MonoBehaviour {
private GameObject camera0;
private GameObject camera1;
private GameObject camera2;
void Start () {
camera0 = GameObject.Find("Camera0");
camera1 = GameObject.Find("Camera1");
camera2 = GameObject.Find("Camera2");
camera1.SetActive(false);
camera2.SetActive(false);
}
void Update () {
if(Input.GetKeyDown(KeyCode.E))
{
camera1.SetActive(false);
camera2.SetActive(false);
camera0.SetActive(true);
}
if(Input.GetKeyDown(KeyCode.R))
{
camera2.SetActive(false);
camera0.SetActive(false);
camera1.SetActive(true);
}
if(Input.GetKeyDown(KeyCode.T))
{
camera1.SetActive(false);
camera0.SetActive(false);
camera2.SetActive(true);
}
}
void OnGUI()
{
if(GUILayout.Button("C1",GUILayout.Height(50)))
{
camera1.SetActive(false);
camera2.SetActive(false);
camera0.SetActive(true);
}
if(GUILayout.Button("C2",GUILayout.Height(50)))
{
camera2.SetActive(false);
camera0.SetActive(false);
camera1.SetActive(true);
}
if(GUILayout.Button("C3",GUILayout.Height(50)))
{
camera1.SetActive(false);
camera0.SetActive(false);
camera2.SetActive(true);
}
}
}
當然了,如果攝像機比較多的話,我們可以偷個懶,用如下的方式:
public void CloseCameras()
{
camera1.SetActive(false);
camera2.SetActive(false);
camera0.SetActive(false);
}
void Update () {
if(Input.GetKeyDown(KeyCode.E))
{
CloseCameras();
camera0.SetActive(true);
}
if(Input.GetKeyDown(KeyCode.R))
{
CloseCameras();
camera1.SetActive(true);
}
if(Input.GetKeyDown(KeyCode.T))
{
CloseCameras();
camera2.SetActive(true);
}
}
只要注意到了“關閉所有攝像機”和“只打開使用的攝像機”,應該就沒啥問題了~
最後是效果的展示: