How to have MainCamera occlude BackgroundCamera?

Forgive my ignorance, but I’m still very new to all this. I’m working on a 2D game, and I added a parallax background consisting of three layers of dynamically-generated stars. I didn’t want to go crazy with background game objects, so when one star exits a viewport edge, it repositions itself at the opposite edge, for an “infinite scroll” type of effect with the background. Because the player can also zoom in and out, and I definitely didn’t want the background also zooming and out with it, the background couldn’t be rendered by the MainCamera. Unless I just misunderstood something? So I created a BackgroundCamera, set it to render only the Background layer, set the MainCamera to render everything else, and made the BackgroundCamera a child of the MainCamera for positioning. This was the result:

9753646--1396225--upload_2024-4-6_9-8-38.gif

At first, I was extatic at having pulled this off given my lack of experience. Then I noticed that the starfield background is seemingly being rendered above the main scene objects, despite the main scene objects having a higher z-index. It’s hard to tell in this recording, but when the ship passes over a star (the larger white star in the upper-right corner is pretty easy to see), the star isn’t hidden behind the ship as expected. After a few minutes of thinking, it makes sense, given that I’m using two cameras at the same time. Maybe that’s not at all the right way to do this, I don’t know.

If the ship sprite passes in front of a star, it should actually pass in front of the star. How can I either a) change how I architected this, or b) make what the MainCamera renders occlude what the BackgroundCamera can render in order to achieve this result? Thanks!

z-index only applies to objects rendered by the same camera.

Cameras have a “depth” value, that determines which camera is rendered first. You want to render the stars camera first, then the ship(s) camera on top. See: Unity - Manual: Camera component

Thank you! I couldn’t find a “Depth” field in the Inspector, but after more closely reading the tooltips of each field, I found “Priority,” which looks to have replaced “Depth.” I also had to set the MainCamera’s background to Uninitialized.