-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDynamicSort.cs
More file actions
45 lines (37 loc) · 1.04 KB
/
DynamicSort.cs
File metadata and controls
45 lines (37 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using UnityEngine;
public class DynamicSort : MonoBehaviour {
[SerializeField]
private bool staticSort;
[SerializeField]
private bool useLocalPos = true;
[SerializeField]
private int numParents;
[SerializeField]
private int offset;
[SerializeField]
private string sortingLayerName = "Dynamic";
private SpriteRenderer spriteRenderer;
private Transform transUsing;
private void Awake() {
spriteRenderer = GetComponent<SpriteRenderer>();
transUsing = GetParent(transform, numParents);
spriteRenderer.sortingLayerName = sortingLayerName;
if (staticSort) {
SetOrder();
enabled = false;
}
}
private void Update() {
if (!WorldControl.IsPaused)
SetOrder();
}
public void SetOrder() {
spriteRenderer.sortingOrder = GetOrder(useLocalPos?transUsing.localPosition.y : transUsing.position.y);
}
public int GetOrder(float yVal) => Mathf.RoundToInt(yVal * -100) + offset;
private Transform GetParent(Transform child, int num) {
if (num == 0 || !child.parent)
return child;
return GetParent(child.parent, num - 1);
}
}