using UnityEngine;

[RequireComponent(typeof(SpriteRenderer))]
[ExecuteAlways]
public class SortByY : MonoBehaviour
{
    [SerializeField] Transform anchor;
    [SerializeField] int factor = 100;

    SpriteRenderer sr;

    void OnEnable()
    {
        sr = GetComponent<SpriteRenderer>();
        if (anchor == null) anchor = transform;
    }

    void LateUpdate()
    {
        if (sr == null) sr = GetComponent<SpriteRenderer>();
        if (anchor == null) anchor = transform;
        sr.sortingOrder = -Mathf.RoundToInt(anchor.position.y * factor);
    }
}
