Search Unity

How to switch to a copy of the main camera

Discussion in 'Getting Started' started by prayshouse, Sep 28, 2017.

  1. prayshouse

    prayshouse

    Joined:
    Sep 11, 2017
    Posts:
    27
    Hi, everyone.
    First, I have a main camera. Then I would like to replace the main camera with a second camera binding a new shader. So I write the code for the second camera as following:
    Code (CSharp):
    1. void LateUpdate() {
    2.     ...
    3.     Camera main = Camera.main;
    4.     secondCamera.CopyFrom(main)
    5.     secondCamera.SetReplacementShader(replacementShader, null);
    6.     transform.position = main.transform.postition;
    7.     transform.rotation = main.transform.rotation;
    8.     ...
    9. }
    Then the matter comes. I want to switch the camera from the main camera to the second camera. I tried to use mainCamera.SetActive(false) and mainCamera.enabled = false, but the both will result in an error: "Camera to copy from mush not be null". Can you tell me a better way to switch them?
     
  2. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,619
    Camera.main returns the Camera that is tagged as "MainCamera". As far as I know, Unity is doing a FindWithTag every time you access Camera.main.

    If multiple GameObject's are active with the "MainCamera" tag, I guess it's pretty much undefined which one is returned. You want to make sure only a single active GameObject with that tag exists at any time.

    Setting the tag through C# can be done via gameObject.tag.
     
  3. jchester07

    jchester07

    Joined:
    Jun 28, 2016
    Posts:
    24
    Here's how I'd do it assuming you switch cams when mouse button is clicked.
    Code (CSharp):
    1. Camera mainCam;
    2. bool switched = false;
    3.  
    4. void Start()
    5. {
    6.     mainCam = Camera.main;
    7. }
    8.  
    9. void Update()
    10. {
    11.     if(Input.GetButtonDown("Fire1") && !switched){
    12.         SwitchToSecondCam();
    13.     }
    14. }
    15.  
    16. void SwitchToSecondCam()
    17. {
    18.     secondCamera.CopyFrom(mainCam)
    19.     secondCamera.SetReplacementShader(replacementShader, null);
    20.     mainCam.enabled = false;
    21.     switched = true;
    22. }
    Take note that in your code, you are copying the main camera every frame. When you disable the main camera, you don't have any active cam tagged sa MainCamera to copy from.
    I don't know the rest of you're code but based on your statement, secondCamera.CopyFrom(main) should be called only once when you switch cam.