版本: Unity 6 (6000.0)
语言英语
  • C#

Renderer.sortingOrder

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交的内容,但我们确实会阅读用户提出的每项建议变更,并在适用的情况下进行更新。

关闭

提交失败

由于某种原因,您的建议更改无法提交。请<a>稍后重试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

public int sortingOrder;

描述

渲染器在排序层中的顺序。

您可以在它们的 SpriteRenderer 组件中将游戏对象分组到层中。这被称为 SortingLayer。排序顺序决定每个游戏对象在每个排序层中的渲染器中的优先级。您赋予它的数字越低,游戏对象在后面的位置出现。数字越高,游戏对象看起来越靠近相机。这在创建 2D 卷轴游戏时非常有效,因为您可能希望在同一层上使用某些游戏对象,但某些部分出现在其他部分的前面,例如,将云分层并使它们出现在天空的前面。

注意: 该值必须介于 -32768 和 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(); } }