유니티 Order in Layer 스크립트 - yuniti Order in Layer seukeulibteu

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(); } }

유니티 Order in Layer 스크립트 - yuniti Order in Layer seukeulibteu

최근에 진행하는 프로젝트에서 플레이어 캐릭터가 돌아다니는 상황에서

건물 오브젝트 혹은 다른 오브젝트과 붙어있을때 랜더링 순서가 맞지않아 고민해본 결과

해당 오브젝트의 position.y값으로 레이어 order값을 변경시켜 건물의 앞에서 앞으로 뒤에선 뒤로

랜더링되도록 구현하였습니다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// SpriteRenderer 필수
[RequireComponent(typeof(SpriteRenderer))]
public class ObjectLayerSetter : MonoBehaviour
{
    private SpriteRenderer spriteRenderer = null;

    private void Awake() {
        this.spriteRenderer = this.GetComponent<SpriteRenderer>();
    }
    private void OnEnable()
    {
    	// 레이어 이름이 Object일때만 호출, 이름은 원하는 이름으로 변경가능
        if(this.spriteRenderer.sortingLayerName != "Object") { return;}

        this.StopAllCoroutines();
        this.StartCoroutine(this.SetLayer());
    }
    private IEnumerator SetLayer()
    {
        while (true)
        {
        	// sortingOrder를 y값으로 계속 변경해준다.
            yield return new WaitForEndOfFrame();
            this.spriteRenderer.sortingOrder = -(int)this.transform.position.y;
        }
    }

    private void OnDisable()
    {
        this.StopAllCoroutines();
    }
}
유니티 Order in Layer 스크립트 - yuniti Order in Layer seukeulibteu
스크립트가 붙으면 SpriteRenderer가 무조건 존재해야합니다.
유니티 Order in Layer 스크립트 - yuniti Order in Layer seukeulibteu
SortingLayer 이름에 Object가 없으면 추가해줍시다.
유니티 Order in Layer 스크립트 - yuniti Order in Layer seukeulibteu
이름 Object 추가
유니티 Order in Layer 스크립트 - yuniti Order in Layer seukeulibteu
한가지 중요한 포인트가 있다면 이미지 리소스에 pivot을 bottom으로 잡아줘야 벽처럼 동작합니다.