Multiple camera switching code in unity3d

Multiple camera switching code in unity3d

   脚本代码将依据按下的键盘上的 1、2 和 3决定启用对应摄像机的AudioListener 和 camera 组件,
   禁用其余两部摄像机的 AudioListener 和 camera 组件,因此看到不同的视图。

1. Create multiple cameras (different locations).

2. Create an empty object and hang our new script Camera Switch to control the switching of the camera.

3. In Caneras, Size is the total number of cameras. Drag and drop the established cameras into Element. In Shotcuts, Size is the total number of buttons to control the cameras. 1, 2, and 3 respectively represent the use of digital keys to control and display Camera1, Camera2, and Camera3 .insert image description here

The code is as follows (example):

using UnityEngine;
using System.Collections;

public class Camera Switch: MonoBehaviour
{
    
    

    public GameObject[] cameras;
    public string[] shotcuts;
    public bool changeAudioListener = true;

    void Update()
    {
    
    
        int i = 0;
        for (i = 0; i < cameras.Length; i++)
        {
    
    
            if (Input.GetKeyUp(shotcuts[i]))
                SwitchCamera(i);
        }
    }

    void SwitchCamera(int index)
    {
    
    
        int i = 0;
        for (i = 0; i < cameras.Length; i++)
        {
    
    
            if (i != index)
            {
    
    
                if (changeAudioListener)
                {
    
    
                    cameras[i].GetComponent<AudioListener>().enabled = false;
                }
                cameras[i].GetComponent<Camera>().enabled = false;
            }
            else
            {
    
    
                if (changeAudioListener)
                {
    
    
                    cameras[i].GetComponent<AudioListener>().enabled = true;
                }
                cameras[i].GetComponent<Camera>().enabled = true;
            }
        }
    }
}

Note: The file name is Camera Switch

       自己可以修改文件名。

Guess you like

Origin blog.csdn.net/qq_43238378/article/details/128985090