Reputation: 43
I am trying to understand how Unity decides what to draw first in a 2D game. I could just give everything an order in layer, but I have so many objects that it would be so much easier if it was just drawing in the order of the hierarchy. I could write a script that gives every object its index, but I also want to see it in editor. So the question is, is there an option that I can check so that it uses the order in the hierarchy window as the default sorting order?
Upvotes: 1
Views: 7905
Reputation: 5173
From your last screenshot I could see you are using SpriteRenderer.
The short answer to the question "is there an option that I can check so that it uses the order in the hierarchy window as the default sorting order?" would be no, there isn't by default*.
Sprite renderers calculates which object is in front of others in one of two ways:
order in layer
, as per the docs:Sprite Sort Point This property is only available when the Sprite Renderer’s Draw Mode is set to Simple.
In a 2D project, the Main Camera is set to Orthographic Projection mode by default. In this mode, Unity renders Sprites in the order of their their distance to the camera, along the direction of the Camera’s view.
If you want to keep everything on the same sorting layer/order in layer you can change the order in which the objects appear by moving one of the two objects further away from the camera (this is probably further down the z
axis). For example if your Cashew is on z = 0
, and you place the walnut on z = 1
then the cashew will be drawn on top of the walnut. If Cashew is on z=0
and the walnut is on z = -1
then the walnut will be draw on top (Since negative is closer to the camera). If both of the objects are on z - 0
they are both equally as far away from the camera, so it becomes a coin toss for which object gets drawn in front, as it does not take into account the hierarchy.
sorting layers
, and adjusting the order in layer
in the sprite renderer
component. But you already figured that out.*However, that doesn't mean it cannot be done, technically...
If you feel adventurous there is nothing stopping you from making an editor script that automates setting the order in layer
for you based on the position in the hierarchy. This script would loop through all the objects in your hierarchy, grab the index of the object in the hierarchy, and assign the index to the Order in Layer.
Upvotes: 1
Reputation: 293
I don't think Unity has such feature (https://docs.unity3d.com/Manual/2DSorting.html).
Usually you shall define some Sorting Layers:
and assign Sprite Renderer of each sprite to one of Sorting Layers
Upvotes: 0