Suggest a change
Success!
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
Close
Submission failed
For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
Close
Your name
Your email
Suggestion*
Cancel
Description
Renderer’s order within a sorting layer.
You can group GameObjects into layers in their SpriteRenderer component. This is called the SortingLayer.
The sorting order decides what priority each GameObject has to the Renderer within each Sorting Layer.
The lower the number you give it, the further back the GameObject appears. The higher the number, the closer the GameObject looks to the Camera. This is very effective when creating 2D scroller games, as you may want certain GameObjects on the same layer but certain parts to appear in front of others, for example, layering clouds and making them appear in front of the sky.
Note: The value must be between -32768 and 32767.
//Attach a script like this to a Sprite GameObject (Create>2D Object>Sprite). Assign a Sprite to it in the Sprite field. //Repeat the first step for another two Sprites and make them overlap each other slightly. This shows how the order number changes the view of the Sprites.using UnityEngine; public class MyScript : MonoBehaviour { public int MyOrder; public string MyName; }
//Create a folder named “Editor” (Right click in your Assets folder, Create>Folder) //Put this script in the folder. //This script adds fields to the Inspector of your GameObjects with the MyScript script attached. Edit the fields to change the layer and order number each Sprite belongs to.using UnityEngine; using UnityEditor;
// Custom Editor using SerializedProperties.
[CustomEditor(typeof(MyScript))] public class MeshSortingOrderExample : Editor { SerializedProperty m_Name; SerializedProperty m_Order;
private SpriteRenderer rend;
void OnEnable() { // Fetch the properties from the MyScript script and set up the SerializedProperties. m_Name = serializedObject.FindProperty("MyName"); m_Order = serializedObject.FindProperty("MyOrder"); }
void CheckRenderer() { //Check that the GameObject you select in the hierarchy has a SpriteRenderer component if (Selection.activeGameObject.GetComponent<SpriteRenderer>()) { //Fetch the SpriteRenderer from the selected GameObject rend = Selection.activeGameObject.GetComponent<SpriteRenderer>(); //Change the sorting layer to the name you specify in the TextField //Changes to Default if the name you enter doesn't exist rend.sortingLayerName = m_Name.stringValue; //Change the order (or priority) of the layer rend.sortingOrder = m_Order.intValue; } }
public override void OnInspectorGUI() { // Update the serializedProperty - always do this in the beginning of OnInspectorGUI. serializedObject.Update(); //Create fields for each SerializedProperty EditorGUILayout.PropertyField(m_Name, new GUIContent("Name")); EditorGUILayout.PropertyField(m_Order, new GUIContent("Order")); //Update the name and order of the Renderer properties CheckRenderer();
// Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI. serializedObject.ApplyModifiedProperties(); } }
Как 2d спрайту задавать order in layer в зависимости от y
Здравтсвуйте! У меня проблема, помогите решить, пожалуйста! Короче говоря у меня скрипт генерации 2д леса генерирует лес, но не учитывает слои. То есть корень на листву накладывается и том подобное. Я думал может задавать order in layer в соответствии с координатой у, но я не смог это записать по-человечески. Помогите либо записать, либо скажите как это делается, а то уже 2 дня сижу((( В цикле вайл генерирую геймобжект в которым по сути мой спрайт и является. И ставлю его в радомные координаты. На вот как задавать order in layer вообще не понимаю, что-то читал, всёравно не понял((( Вот код, помогите кто знает.
Используется csharp
int i = 0;
while(i < howmuchtrees)
{
Vector3 position = new Vector3(Random.Range(ZonePosition.x — ZoneRadius, ZonePosition.x + ZoneRadius), Random.Range(ZonePosition.z — ZoneRadius, ZonePosition.z + ZoneRadius), 0); //Вектор с рандомными координатами в пределах зоны
if (!Physics.CheckSphere(position, _TreeDensity))
{
Instantiate(_tree, position, Quaternion.identity) as GameObject;
i++;
}
}
- HammerSmithG1
- UNец
- Сообщения: 22
- Зарегистрирован: 11 июн 2015, 00:58
Re: Как 2d спрайту задавать order in layer в зависимости от y
samana 13 сен 2015, 22:25
Все деревья конечно лучше поместить в массив или в отдельного родителя, чтобы было потом удобно манипулировать этими деревьями.
И например, если все деревья у вас имеют одного родителя, то можно создать метод, который отсортирует их, допустим такой:
Используется csharp
using System.Collections.Generic;
using System.Linq;
private void sortChildren()
{
//создаём массив, куда поместим всех детей объекта _someParent
Transform[] children = new Transform[_someParent.transform.childCount];
//помещаем детей в массив, созданный выше
for (int i = 0; i < _someParent.transform.childCount; i++)
{
children[i] = _someParent.transform.GetChild(i);
}
//сортируем массив по положению Y у ребёнка. У тех кого Y больше, будут в начале массива.
//так как задача — дерево по Y ниже, должно перекрывать дерево которое выше по Y,
//значит sortingOrder у дерева ниже, должен быть больше.
children = children.OrderByDescending(c => c.transform.position.y).ToArray();
//перебираем уже правильно отсортированный массив с детьми
//и назначем каждому свой sortingOrder
for (int i = 0; i < children.Length; i++)
{
children[i].GetComponent<SpriteRenderer>().sortingOrder = i;
}
}
-
samana - Адепт
- Сообщения: 4733
- Зарегистрирован: 21 фев 2015, 13:00
- Откуда: Днепропетровск
Вернуться в Почемучка
Кто сейчас на конференции
Сейчас этот форум просматривают: GoGo.Ru [Bot], Yandex [Bot] и гости: 30
Managing the order of 2D sprites and objects on the screen in Unity can be very straightforward.
After all, it’s easy enough to place background objects further away from the camera, so that they’re rendered behind other objects in the scene that are closer.
However, while this may be all you need to do, using distance alone to manage how your game’s 2D objects are sorted can sometimes become difficult to manage.
For example, what if you want to combine multiple sprites to create a character?
Or create a game with a top-down sorting perspective.
And, as your game grows, how can you manage the order of many different objects, easily?
Exactly how you manage the order of objects in your game will depend on what it is you’re trying to do but, for the most part, Unity’s built-in sorting tools and components can make it much, much easier to manage which objects are supposed to go on top, and which go on the bottom.
In this article, you’ll learn about the different methods for sorting objects in 2D and 3D, so that you can choose what will work for your game.
Here’s what you’ll find on this page:
- How to sort 2D objects in Unity
- How to use Sorting Layers in Unity
- How to use Sorting Groups in Unity
- How to manage Sorting Layers using a script
- How to sort 2D sprites by distance in Unity (using a custom camera axis)
- Using Sorting Layers in 3D in Unity
- How to sort 3D objects (using a second camera)
- How to sort 3D objects (using a shader)
So how do Unity’s sorting tools work?
How to sort 2D objects in Unity
Normally, objects in Unity are displayed on the screen in their order of distance from the camera.
Just as you might expect.
However, while this makes a lot of sense for 3D geometry, for 2D sprites, it can cause some problems.
When building a 2D game, it’s not uncommon to place all of your sprites at the same physical distance from the camera.
When making a 2D game, it’s common to place all of your sprites on a single, flat plane.
Which means that Unity can’t know which sprites should be displayed in the foreground and which should be placed in the background.
This problem can be simple to fix, just move the background back and the foreground forward.
Problem solved, right?
Using physical distance to manage the order of rendered objects can work just fine and, if it works for you, it may be all you need to do.
However, you may find it easier to group sections of your game into specific render layers, such as the sky, the background and different parts of the environment, so that objects are always rendered in their correct order, no matter how far away they are from the camera.
Which is where Sorting Layers come in…
How to use Sorting Layers in Unity
Sorting Layers in Unity allow you to control the render order of 2D objects, regardless of their physical distance from the camera.
This can be useful for placing objects in the background or foreground, without needing to move the object to a physical position.
So, how do they work?
Every visible object in Unity has some kind of renderer component that’s used to display it in the game.
2D renderers, such as Sprite Renderers allow you to set a Sorting Layer for the sprite, as well an Order in Layer value.
Some renderers, such as 2D Sprite Renderers, allow you to specify a Sorting Layer and order value.
Unity uses this information, as well as other data, such as the object’s position, to work out a sorting order.
First, Unity will use the renderer’s Sorting Layer and, after that, it will use the Order in Layer value, which is a numerical value that’s used to sort objects that are on the same Sorting Layer.
If two objects are on the same Sorting Layer and also have the same Order in Layer value, then the object’s distance from the camera will be used to decide its order, specifically the distance between the camera and the sprite’s Sort Point.
The Sort Point of a sprite can be either the centre, or its pivot point, which can be set in the sprite’s import settings.
This is why, by default, sprites are ordered by distance, as every new object uses the same default Sorting Layer with the same default Order in Layer value, which is 0.
Adding a Sorting Layer, or changing the Order in Layer value, overrides the object’s distance, allowing you to display objects in front of others, even if they’re closer to the camera.
So how can you add a new Sorting Layer?
How to add a new Sorting Layer in Unity
Sorting Layers can be added and reordered in the Tags and Layers settings, which you’ll find in the Project Settings window, under Tags and Layers, or from the Sorting Layer dropdown which will open the Tags and Layers tab in the Inspector.
The quickest way to get to the Tags and Layers settings is to simply click on the Sorting Layer field and select Add Sorting Layer.
By default, there’s only one Sorting Layer, the Default layer, which can’t be removed.
To add more, simply click the plus symbol and drag the layers into the order you want. Layers at the bottom of the list will be shown in front of layers at the top.
Sorting Layers are ordered from top to bottom, where layers on the bottom are shown in front of layers at the top.
While it’s possible to manage the sorting order of all of your objects on a single Sorting Layer, it can be easier to add extra layers for groups of objects that you know will always need to be in front of or behind other objects in the scene.
For example, I could add a Background and a Foreground Sorting Layer for everything that should be displayed in front of or behind the player and then simply leave everything else on the Default layer.
Like this:
Grouping objects into layers that will always be behind or in front of other objects can make it easier to manage how they are displayed on the screen.
Sorting Layers vs Layers in Unity
There’s a difference between Sorting Layers, which are used by some renderer components to manage 2D sorting order, and Layers, which are an organisational tool that can be used on any game object.
Sorting Layers are specifically used to manage the rendering order of 2D objects, such as sprites, allowing you to display objects in front of other objects, regardless of their physical position in the scene.
Layers, on the other hand, are used to group specific types of game object together for organisational reasons. You’d typically use Layers to include or exclude certain types of object. Raycast functions, for example, allow you to selectively ignore certain layers, which can be useful for performing a ground check without hitting your player’s own collider.
Different to Sorting Layers, Object Layers are used as a way to include or exclude groups of game objects from certain functions and to filter camera views.
Sorting Layers and the Order in Layer value can be useful for easily managing the order of sprites in your scene.
Sometimes, however, particularly if you’re creating objects made up of many different sprites, managing them with individual values can be difficult to do.
What’s more, if the individual sprites of one object are on the same layer as other objects in the scene, you’ll need to create Order in Layer values that are relative to other objects, so that they don’t overlap in confusing ways.
Which is no easier than changing the distance of every object.
That is, unless, you use Sorting Groups.
How to use Sorting Groups in Unity
Sorting Groups allow you to change and manage the sorting order of multiple Sprite Renderers, from a single component.
Put simply, a Sorting Group allows you to treat a collection of Sprite Renderers as one object, making it easier to manage.
Sorting Groups allow you to treat multiple renderers as one.
For example, if you create a character that’s made up of many individual sprites, it can be difficult to manage how those sprites interact with other sprites on the same layer.
Which could cause only some parts of a character to be rendered above parts of a different character when they overlap, depending on their Order in Layer values.
Adding a Sorting Group component to the character’s root object solves this problem by treating the object’s many different renderers as one combined object.
While Unity will still use the Sort Layer and order settings of each individual renderer, they are no longer sorted relative to other objects in the scene.
Instead, they are sorted relative to their parent Sorting Group, regardless of their Sorting Layer or order value.
Which means that, when using a Sorting Group, an object’s individual renderers can be sorted relative to itself, using Order in Layer values and even different Sorting Layers, while the Sorting Group manages the order position relative to other objects.
This allows you to create complex objects, made up of many different sprites, but that will only ever be in front of, or behind, other objects as a whole.
How to manage Sorting Layers using a script
While you would normally set an object’s sorting values ahead of time, such as when creating an object from a Prefab, you may want to set or change an object’s Sorting Layer and order value using a script.
Luckily, it’s fairly straightforward to set an object’s Sorting Layer in scripting. All you’ll need is a reference to its Renderer component.
There are many different types of renderer, such as Mesh Renderers, which display objects in 3D and Sprite Renderers, for 2D graphics.
However, they all inherit from the Renderer class, which also contains the Sorting Layer and Order in Layer properties.
So, while not all renderers support Sorting Layers, which only work with 2D renderers such as Sprite Renderers and Tilemap Renderers, you won’t need a specific reference to a Sprite Renderer to use them in a script.
You can simply get a reference to the base Renderer class instead.
Like this:
Renderer myRenderer = GetComponent<Renderer>();
You can then use that reference to set either the Sorting Layer, using the layer’s name, or the Order in Layer value.
Like this:
void Start()
{
Renderer myRenderer = GetComponent<Renderer>();
myRenderer.sortingLayerName = "Top";
myRenderer.sortingOrder = 10;
}
How to use the Sorting Layer ID in Unity
You may have noticed that, in addition to the Sorting Layer name and order properties, Renderers in Unity also have a Sorting Layer ID property.
However, while you might assume that the Sorting Layer ID value relates to the numerical order of the Sorting Layers, it is, in fact, a unique identifier that can’t be directly used to manage an object’s layer. This is because, while the default Sorting Layer will always have an ID value of zero, new layers will have uniquely created IDs that are assigned internally.
However, it is still possible to assign a Sorting Layer based on its position in the layer list.
This works by retrieving all of the project’s Sorting Layers as an array and then simply returning the one that you want using its index position.
For example, I could use this method to get the bottom layer…
Like this:
void Start()
{
// Sets the renderer to display on the first layer in the list
Renderer myrenderer = GetComponent<Renderer>();
myrenderer.sortingLayerID = SortingLayer.layers[0].id;
}
Or the top layer…
Like this:
void Start()
{
// Sets the renderer to display on the last layer in the list
Renderer myrenderer = GetComponent<Renderer>();
myrenderer.sortingLayerID = SortingLayer.layers[SortingLayer.layers.Length-1].id;
}
This can be useful for sorting a Renderer by a specific layer position, such as the top or bottom, without needing to know the name of the layer first.
How to sort 2D sprites by distance in Unity (using a custom camera axis)
While Sorting Layers can be incredibly useful for managing 2D sprite order in Unity, an object’s distance from the camera can still be a vital tool for managing how objects are displayed.
For example, a side-on 2D game may not need to consider an object’s physical distance from the camera at all, and, instead, the order of objects can be managed using only Sorting Layers.
However, some types of 2D games may still incorporate a perception of depth, where the movement of an object past another means that it should be rendered behind it.
For example, in a 2D game with an overhead perspective, moving up moves the player into the background. Objects that are lower than the player are technically in front of them, while higher objects are behind them.
Some 2D games use perspective in a different way, where objects at the top of the screen are behind objects at the bottom.
While dynamically sorting objects in this way using layers could become difficult, it’s possible, instead, to simply use a camera’s normal method of sorting by distance, just from a different angle.
By default, Renderers in Unity are typically ordered according to two different queues: The Opaque Queue, which includes most solid 3D objects and the Transparency Queue, which includes transparent objects and most 2D sprites.
The axis of the Transparency Queue, which is the direction in which objects are sorted, defaults to the direction between the object being rendered and the camera’s position for perspective cameras or simply the direction of the camera for orthographic cameras.
Setting the axis to a custom value, however, allows you to change the direction of the Transparency queue, from the default back to front to top to bottom, for example.
This can be done in the Project Settings window, under the Graphics tab:
Changing the Camera’s Transparency Axis changes the sorting direction, in this case from top to bottom.
Or from a script,
Like this:
void Start()
{
Camera.main.transparencySortMode = TransparencySortMode.CustomAxis;
Camera.main.transparencySortAxis = Vector3.up;
}
When sorting sprites in this way, you’ll often need to make sure that the sprite’s pivot point is anchored at the position it can be passed at, as this is the point on the sprite that Unity will use to determine if it is in front of or behind another object.
The pivot position of a sprite can be changed in its Import Settings and selected on the Renderer itself, where you’ll have the option to choose the sprite’s pivot or the centre of the sprite as a Sort Point.
By default Unity uses the centre of a sprite to determine where it is, however you can change this to use the sprite’s pivot point instead.
Typically, when creating top-down distance, this will be at the bottom of the sprite.
You can change a sprite’s pivot point in the sprite’s Import Settings panel.
For example, both a player object and a tree are likely to be connected to the world at their base, meaning that if the bottom of the player is higher than the bottom of the tree, it should be rendered behind it.
When using a top-down camera axis, pivot points that are higher are considered to be behind pivot points that are lower. In this case, the objects are grounded at their base, so the pivot points are measured from the bottom of the sprite.
However, elevated objects, or taller objects that are made up of multiple sprites (such as the top and bottom half of a tree), may need to be anchored at a custom distance, lower than the bottom of their sprite, so that they render correctly.
The pivot point of this sprite is set to a custom distance that extends below the bottom of the sprite, allowing an object to be behind it when it’s past the bottom of the tree.
Using a combination of camera distance, Sorting Layers and sprite pivot points can make it significantly easier to manage how 2D objects are displayed in your game.
But what if you want to use Sorting Layers with 3D objects?
Is it possible to use Unity’s 2D sorting tools with 3D Mesh Renderers?
The Sorting Layers and Order in Layer values that are used to sort 2D renderers in Unity don’t work with 3D Mesh Renderers.
A lot of the time, this may not be a problem, however, there may be times when you want to display a 3D object in front of another, regardless of its distance, in order to create a specific visual effect.
So, if you can’t use Sorting Layers, what can you do?
While Unity’s 2D sorting tools aren’t compatible with 3D renderers, it’s still possible to create visual effects that place one or more objects in front of others in the scene, even if they’re further from the camera.
Exactly how you do this depends on the complexity of the effect that you’re trying to achieve.
For example, if you want to display multiple objects above other parts of a scene, one method is to use a second camera.
How to sort 3D objects (using a second camera)
One option for displaying 3D objects in front of other objects in Unity is to use a second camera.
This works by adding a duplicate camera in the scene, that’s set to render on top of the original camera’s image, but that will only display certain objects, showing the rest of the scene below.
By using two cameras at the same position, it’s possible to separate what each camera sees and then reorder the layers.
Here’s how to do it…
First, add a second camera to your scene (you may wish to make both of the cameras children of one game object, so that you can control them more easily together).
Next, create a new Object Layer that will hold any ‘Always on Top’ objects.
On the duplicate camera, click the Culling Mask dropdown and deselect all other Object Layers, so that the Always on Top layer is the only one that’s being rendered (you may wish to disable this layer on the original camera).
Then, to display the camera’s image above the original, set the Depth value to a higher number than the main camera.
Finally, click the Clear Flags dropdown and select Depth Only.
The Clear Flags setting essentially decides what the camera will show in an empty space.
Usually, this is used to show a Skybox, or even just a solid colour. Setting it to Depth Only allows the original camera to display beneath any objects rendered by the duplicate camera.
Now, any objects that you add to the Always on Top Layer will be shown above all other objects.
Using a second camera can be a useful way to superimpose objects onto an existing view.
However, it’s not the only method.
For example, it’s possible to change how an object is displayed by modifying the material’s shader, forcing Unity to ignore its depth.
How to sort 3D objects (using a shader)
It’s possible to render a 3D object in front of another object in Unity, without using multiple cameras, by disabling ZTest.
ZTest is a shader command that checks geometry distance to see if it should be rendered or not based on what’s in front of it, rejecting geometry that fails the test, because it’s behind another object.
Setting ZTest to Always or Off forces the geometry to always pass the test, even if it’s behind another object, displaying it in front.
It works by adding the ZTest command to a custom shader script.
Like this:
Shader "Custom/AlwaysOnTop"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
}
SubShader
{
ZTest Always
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D _MainTex;
struct Input
{
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
void surf (Input IN, inout SurfaceOutputStandard o)
{
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
In this example, I’ve created a new shader based on the Standard Surface Shader and simply added the ZTest command.
Any material that uses the shader will then be displayed in front of other objects, even if they’re closer to the camera.
Now it’s your turn
Now I want to hear from you.
How are you managing sorting order in your game?
Are you using Sorting Layers to combine objects into easy to manage groups?
Or do you prefer to use distance to handle which objects are displayed first?
And what have you learned about sorting objects in Unity that you know others will find useful?
Whatever it is, let me know by leaving a comment.
Get Game Development Tips, Straight to Your inbox
Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.
My favourite time-saving Unity assets
Rewired (the best input management system)
Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.
DOTween Pro (should be built into Unity)
An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.
Easy Save (there’s no reason not to use it)
Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.
Overview
Unity sorts Renderers according to a priority order that depends on their types and usages. You can specify the render order of Renderers through their Render Queue. In general, there are two main queues: the Opaque queue and the Transparent queue. 2D Renderers are mainly within the Transparent queue, and include the Sprite RendererA component that lets you display images as Sprites for use in both 2D and 3D scenes. More info
See in Glossary, Tilemap Renderer, and Sprite Shape Renderer types.
Transparent Queue Sorting Order by Priority
2D Renderers within the Transparent Queue generally follow the priority order below:
- Sorting Layer and Order in Layer
- Specify Render Queue
-
Distance to Camera
- Perspective/Orthographic
- Custom Axis sort mode
- Sprite Sort Point
- Sorting Group
- Material/Shader
- A Tiebreaker occurs when multiple Renderers have the same sorting priorities.
There are other factors which can cause the sorting order to differ from the regular priority order. These factors vary from project to project.
Sorting Layer and Order in Layer
The Sorting Layer and Order in Layer (in the Renderer’s Property settings) are available to all 2D Renderers through the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary window or via the Unity Scripting API. Set the Renderer to an existing Sorting Layer or create a new one to determine its priority in the renderingThe process of drawing graphics to the screen (or to a render texture). By default, the main camera in Unity renders its view to the screen. More info
See in Glossary queue. Change the value of the Order in Layer to set the Renderer’s priority among other Renderers within the same Sorting Layer.
Specify Render Queue
You can specify the Render Queue type of the Renderer in its Material settings or in the ShaderA program that runs on the GPU. More info
See in Glossary settings of its Material. This is useful for grouping and sorting Renderers which are using different Materials. Refer to documentation on ShaderLab: SubShader Tags for more details.
Distance to Camera
The Camera component sorts Renderers based on its Projection setting. The two options are Perspective and Orthographic.
Perspective
In this mode, the sorting distance of a Renderer is the direct distance of the Renderer from the CameraA component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
See in Glossary’s position.
Orthographic
The sorting distance of a Renderer is the distance between the position of the Renderer and the Camera along the Camera’s view direction. For the default 2D setting, this is along the (0, 0, 1) axis.
When you set the Camera component to Perspective or Orthographic, Unity automatically sets the Camera’s TransparencySortMode to match the selected mode. You can set the Transparency Sort Mode manually in two ways:
- Open the Project SettingsA broad collection of settings which allow you to configure how Physics, Audio, Networking, Graphics, Input and many other areas of your project behave. More info
See in Glossary and go to Graphics, then under Camera Settings use Transparent Sort Mode - Set the Camera’s TransparencySortMode via the Scripting API.
The Camera Transparency Sort Mode settings are under the Graphics category in the Project Settings (main menu: Edit > Project Settings > Graphics). When this is set to Default, a Camera component’s Projection setting take priority. When this is set to an option other than Default, the Camera component’s Projection setting remains the same, but the Camera’s Transparency Sort Mode changes to that option.
An additional option available through the Project settings and via the Scripting API is the Custom Axis sort mode.
Custom Axis sort mode
Select this mode to sort Renderers based on their distance along the custom axis you set in the Project settings (main menu: Edit > Projecting Settings > Graphics > Transparency Sort Axis). This is commonly used in projects with Isometric Tilemaps to sort and render the Tile Sprites correctly on the Tilemap. Refer to Creating an Isometric Tilemap for further information.
Sprite Sort Point
By default, a SpriteA 2D graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development. More info
See in Glossary’s Sort Point is set to its Center, and Unity measures the distance between the camera’s Transform position and the Center of the Sprite to determine their render order during sorting. An alternate option is to set a Sprite’s Sort Point to its Pivot position in World Space. Select the Pivot option in the Sprite’s Sprite Renderer property settings and edit the Sprite’s Pivot position in the Sprite Editor.
Sorting Group
The Sorting Group is a component that groups Renderers which share a common root together for sorting purposes. All Renderers within the same Sorting Group share the same Sorting Layer, Order in Layer, and Distance to Camera. Refer to documentation on the Sorting Group component and its settings for more details.
Material/Shader
Unity sorts Renderers with the same Material settings together for more efficient rendering performance, such as with dynamic batchingAn automatic Unity process which attempts to render multiple meshes as if they were a single mesh for optimized graphics performance. The technique transforms all of the GameObject vertices on the CPU and groups many similar vertices together. More info
See in Glossary.
Tiebreaker
When multiple Renderers have identical sorting priority, the tiebreaker is the order that Unity places the Renderers in the Render Queue. Because this is an internal process that you have no control over, you should use the sorting options (such as Sorting Layers and Sorting Groups) to make sure all Renderers have distinct sorting priorities.
Copyright © 2020 Unity Technologies
优美缔软件(上海)有限公司 版权所有
«Unity»、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。