본문 바로가기

카테고리 없음

unity 2d 캐릭터 sortingorder 실시간 조정

y값 기준으로 아래있는건 더 앞에 그리기

 

using UnityEngine;
using System.Collections.Generic;

public class SortingOrderManager : MonoBehaviour
{
    public static SortingOrderManager Instance;

    private List<SpriteRenderer> characterRenderers = new List<SpriteRenderer>();

    public float yOffsetMultiplier = 100;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void RegisterCharacter(SpriteRenderer renderer)
    {
        if (!characterRenderers.Contains(renderer))
        {
            characterRenderers.Add(renderer);
        }
    }

    public void UnregisterCharacter(SpriteRenderer renderer)
    {
        if (characterRenderers.Contains(renderer))
        {
            characterRenderers.Remove(renderer);
        }
    }

    void LateUpdate()
    {
        foreach (var renderer in characterRenderers)
        {
            if (renderer != null)
            {
                renderer.sortingOrder = Mathf.RoundToInt(renderer.transform.position.y * yOffsetMultiplier) * -1;

                 //이거 abs로해서 절댓값으로 해줄것
            }
        }
    }
}

 

 

 

 

 

using UnityEngine;

[RequireComponent(typeof(SpriteRenderer))]
public class CharacterRegistration : MonoBehaviour
{
    private SpriteRenderer spriteRenderer;

    void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        if (SortingOrderManager.Instance != null)
        {
            SortingOrderManager.Instance.RegisterCharacter(spriteRenderer);
        }
    }

    void OnDestroy()
    {
        if (SortingOrderManager.Instance != null)
        {
            SortingOrderManager.Instance.UnregisterCharacter(spriteRenderer);
        }
    }
}