Learning how to work with cameras

I want to know if I am doing this right. I am working on this scene where I have three different cameras. One if them is the main camera which is set to start at default. Then it changes to the next camera when the user is done and presses a button.

Right now I have three camera variables called: viewport1, viewport2, viewport3

In my start function I have all three viewports initialized as

Viewport1 = GameObject.Find(“MainCamera”).camera;
Viewport2 = GameObject.Find(“IsometricCamera”).camera;
ViewPort3 = GameObject.Find("TopView).camera;

Then I started enabling them right afterwards in the same start function:
Viewport1.enabled = true;
ViewPort2.enabled = false;
ViewPort3. Enabled = false;

In an Update I set them up in a switch statement where I enable / disable them as the user progresses. But the thing is that I am facing a certain problem:

For starters I get a null reference exception. That points to the first viewport. But if I comment out the line it points to the next viewport and so on. In addition the main camera is no longer the first camera to be set up, it is actually the third viewport camera that is the default camera now.

I also have this class attached to the main camera object.

How do I get rid of this null reference exeption and how do I get the main camera to be the first camera to be loaded?

First you should check to make sure your names are correct for the gameobjects. By default Unity names the MainCamera “Main Camera” with a space. A better approach would be make the cameras public in the class and assign them in the inspector:

class CameraManager
{
     public Camera viewPort1;//assign in inspector
     public Camera viewPort2;//assign in inspector
     public Camera viewPort3;//assign in inspector

     void Start()
     {
          viewPort1.enabled = true;
          viewPort2.enabled = false;
          viewPort3.enabled = false;
     }

     void Update()
     {
           //TODO:turn cameras on and off here
     }
}

Next, you should not have this script on the MainCamera. The reason is when you disable the GameObject Update will not be called on a disabled script. Instead I would create an empty GameObejct and throw the script on it.

The reason your main Camera is not being seen is because the Depth value of the cameras. The lower number camera get rendered first. I think once you get the references sorted out this will fix itself.

I would also check the tag of the cameras. There should only be 1 main Camera tagged in the scene at one time.

Hope this helps…