Search Unity

How to switch to a copy of the main camera

Discussion in 'Scripting' 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. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
    I'm not sure this will be helpful. I've got a setup that let me switch between two different cameras.

    I started by adding a second camera inside my main camera.

    upload_2017-9-27_21-51-28.png

    One is regular and one is orthographic but really anything should do.

    Then I wrote this script.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SwitchCameras : MonoBehaviour
    4. {
    5.   public Camera Main;
    6.   public Camera Alternate;
    7.  
    8.   void Update()
    9.   {
    10.     if (Input.GetKeyUp(KeyCode.C))
    11.       ToggleCamera();
    12.  
    13.     Alternate.enabled = !Main.enabled;
    14.   }
    15.  
    16.   private void ToggleCamera()
    17.   {
    18.     Main.enabled = !Main.enabled;
    19.   }
    20. }
    21.  
    Then I added it to the main camera, and configured it as follows:

    upload_2017-9-27_21-52-20.png

    When I run the scene, I start with a perspective view.

    upload_2017-9-27_21-53-15.png

    When I tap C, it toggles to orthographic.

    upload_2017-9-27_21-53-42.png

    There's no reason you shouldn't be able to do whatever manipulation you want for the alternate camera before switching it on. The key is to make the camera mono behaviour is enabled for one and not for the other.

    Technically, I think that all the cameras render in some kind of order having to do with their position in the scene hierarchy and a camera expert can probably elaborate on that but this should help you get toward where you want to be going.