Camera.main

Unity · Версия 2020.3 LTS · Scripting · Camera

Camera.main

public static Camera main;

Описание

Первый включенный компонент камеры с тегом "MainCamera" (только для чтения).

Если нет включенного компонента камеры с тегом "MainCamera", это свойство имеет значение null.

Внутренне Unity кэширует все игровые объекты с тегом «MainCamera». Когда вы обращаетесь к этому свойству, Unity возвращает первый допустимый результат из своего кеша. Доступ к этому свойству имеет небольшую нагрузку на ЦП, сравнимую с вызовом GameObject.GetComponent. Если важна производительность ЦП, рассмотрите возможность кэширования этого свойства.

Смотрите так же: Tags

//Place this script on a GameObject to switch between the main Camera and your own second Camera on the press of the "L" key
//Place a second Camera in your Scene and assign it as the "Camera Two" in the Inspector.

using UnityEngine;

public class Example : MonoBehaviour
{
    //This is Main Camera in the SceneCamera m_MainCamera;
    //This is the second Camera and is assigned in inspector
    public Camera m_CameraTwo;

    void Start()
    {
        //This gets the Main Camera from the Scene
        m_MainCamera = Camera.main;
        //This enables Main Camera
        m_MainCamera.enabled = true;
        //Use this to disable secondary Camera
        m_CameraTwo.enabled = false;
    }

    void Update()
    {
        //Press the L Button to switch cameras
        if (Input.GetKeyDown(KeyCode.L))
        {
            //Check that the Main Camera is enabled in the Scene, then switch to the other Camera on a key press
            if (m_MainCamera.enabled)
            {
                //Enable the second Camera
                m_CameraTwo.enabled = true;

                //The Main first Camera is disabled
                m_MainCamera.enabled = false;
            }
            //Otherwise, if the Main Camera is not enabled, switch back to the Main Camera on a key press
            else if (!m_MainCamera.enabled)
            {
                //Disable the second camera
                m_CameraTwo.enabled = false;

                //Enable the Main Camera
                m_MainCamera.enabled = true;
            }
        }
    }
}

Обновлено 17 ноября 2026 г.