unity-game-engineuser-interfacecameraperspectiveorthographic

Unity3D: changing camera from perspective to orthographic hides UI elements


In my project I'm using 2 cameras:

  1. the Main Camera for the scene 3D elements;
  2. a secondary camera for UI elements, which I need(?*) since I want to render 3D objects inside the UI (I followed this YouTube tutorial).

?* - I'm actually not 100% sure if that's the only and/or correct way to render 3D objects in UI, but I haven't found any other solution.

Unity Inspector

Main Camera

Here's the Inspector of my Main Camera (Perspective Projection):
enter image description here

Orthographic Camera

Inspector of one of the orthographic cameras:
enter image description here

UI Camera

Inspector of the UI camera (also orthographic):
enter image description here

Canvas Details

Inspector of the canvas I'm using for the UI:
enter image description here

I'm trying to make a sort of switch for different orthogonal projections, that makes use of different cameras to change the perspective. Therefore I made a dropdown UI element that seems to work fine: I used the gameobject.SetActive(bool) method to switch camera, even though the docs say to use the enabled property to switch cameras, because that wasn't working.

Switch Camera Script

public class ChangeCamera : MonoBehaviour
{
    public List<Camera> cameras;

    public void SetCamera(int camera)
    {
        for (int i = 0; i < cameras.Count; i++)
        {
            cameras[i].gameObject.SetActive(i == camera);
        }
    }
}

Problem

So far so good. The problem is that, when I switch the camera in Play Mode, the UI disappears.

Demo

1. Perspective Camera

Before switching camera (UI correctly displayed): enter image description here

2. Orthographic Camera

After switching camera to orthogonal (UI disappeared): enter image description here

And that's what I see in the Scene window: enter image description here

Update

Setting the Canvas "Render Mode" to Screen Space - Overlay seems to be solving the problem, but then I'm not able to see the 3D objects in the UI: enter image description here


Solution

  • Turns out it was easier than I thought. Big thanks to derHugo :)

    Problem

    The problem here is the camera depth:

    Since the camera depth controls the cameras rendering order, a camera with a lower depth gets rendered before with a camera with higher depth. Therefore, when I was changing the camera to one of the orthographics one, they were rendered in the same depth of the UI, masking it completely.

    Solution

    I changed the orthographic cameras depth to -1 (the same as the Main Camera), and that solved the problem.
    NB: this had nothing to do with the camera using perspective or orthographic projection.

    Demo

    1. Before

    enter image description here

    2. After

    enter image description here