Forum begins after the advertisement:
-
::Hi folks, here is a Sortable script that you can use to easily sort your 2D sprites in your 2D game. We’ll be creating a video to address this issue very soon:
using UnityEngine;
/// <summary>
/// This is a class that can be subclassed by any other class to make the sprites
/// of the class automatically sort themselves by the y-axis.
/// </summary>
[RequireComponent(typeof(SpriteRenderer))]
public abstract class Sortable : MonoBehaviour
{
SpriteRenderer sorted;
public bool sortingActive = true; // Allows us to deactivate this on certain objects.
public const float MIN_DISTANCE = 0.2f; // Minimum distance before the sorting value updates.
int lastSortOrder = 0;
// Start is called before the first frame update
protected virtual void Start()
{
sorted = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
protected virtual void LateUpdate()
{
if (!sorted || !sortingActive) return;
int newSortOrder = (int)(-transform.position.y / MIN_DISTANCE);
if (lastSortOrder != newSortOrder) {
lastSortOrder = sorted.sortingOrder;
sorted.sortingOrder = newSortOrder;
}
}
}
Advertisement below: