-
-
Notifications
You must be signed in to change notification settings - Fork 102
Home
- How do I fix objects displaying behind the background?
- Error: Cannot implicitly convert type 'Pipes' to 'Pipes[]'
In any game, objects are rendered in a particular order. We usually want objects farthest from the camera, such as the background, to be rendered first, thus all other objects are rendered on top of it. There are 3 common ways to change the render order of objects, with the following priority:
- Sorting Layer
- Order in Layer
- Distance to Camera (Z transform)
The "Sorting Layer" and "Order in Layer" are properties available on the SpriteRenderer
component. However, for this particular game, we used a 3D object for the background and ground because it was a much easier solution to create the parallax and scrolling animation. For this reason, we don't have access to those properties, so we must use the third option.
Change the z-axis position on the Transform
component for each of your objects to set the render order, with the largest value being rendered first. I set my background to 0, the ground to -1, and the player/bird to -2. It's important the player is rendered last so it always displays on top of everything.
You can read more about 2D sorting here: https://docs.unity3d.com/Manual/2DSorting.html
This error is caused by a simple typo I have seen several people make. In the GameManager.cs
script, we have the following line of code in the Play
function to find all of the objects in the scene with the Pipes
script attached to it:
Pipes[] pipes = FindObjectsOfType<Pipes>();
The error is easily caused if you use the singular version of the function FindObjectOfType
rather than the plural version FindObjectsOfType
. By using the plural version, it returns an array of pipes Pipes[]
whereas the singular version returns one instance of Pipes
, hence the error trying to convert between the two. Make sure to use the plural version of the function.
I think part of the confusion stems from "pipes" already being a plural word, even if we have a single instance of it. The Pipes
script represent a single group of pipes, but there are multiple groups within the scene, thus we get an array of them.