Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
unity ui sorting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BillBoard2D : MonoBehaviour {
public Camera m_Camera;
void Update()
{
if (!m_Camera)
m_Camera = Camera.main;
transform.LookAt(transform.position + m_Camera.transform.rotation * Vector3.forward,
m_Camera.transform.rotation * Vector3.up);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowTarget : MonoBehaviour {
public Transform target;
public Vector3 offset;
public float smoothTime = 0.1f;
private float velocity;
private Transform myTransform;
// Use this for initialization
void Awake () {
myTransform = GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
if (target == null) return;
Vector3 pos = target.position + offset;
Vector3 now = myTransform.position;
if (pos.Equals(now)) return;
float distance = Vector3.Distance(pos, now);
float v = Mathf.SmoothDamp(0, distance, ref velocity, smoothTime);
myTransform.position = Vector3.MoveTowards(now, pos, v);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UISortByCamera : MonoBehaviour {
private Transform myTransform;
private List<Pair> childs = new List<Pair>();
public Camera camera;
public struct Pair
{
public Transform target;
public float distance;
public int index;
}
private void Awake()
{
myTransform = GetComponent<Transform>();
if (camera == null)
camera = Camera.main;
}
// Update is called once per frame
void Update () {
if (camera == null) return;
Vector3 cameraPos = camera.transform.position;
Vector3 cameraForward = camera.transform.forward;
float near = camera.nearClipPlane;
childs.Clear();
for(int i = 0, l = myTransform.childCount; i < l; i++)
{
Transform target = myTransform.GetChild(i);
float distance = Vector3.Dot(target.position - cameraPos, cameraForward);
childs.Add(new Pair()
{
target = target,
distance = distance,
index = i
});
}
childs.Sort(SortComparerr);
for (int i = 0, l = childs.Count; i < l; i++)
{
if (childs[i].distance >= near)
childs[i].target.SetAsLastSibling();
}
}
private int SortComparerr(Pair a, Pair b)
{
if (a.distance > b.distance)
return -1;
if (a.distance < b.distance)
return 1;
// List.Sort is unstable
// so make stable sort with index
return a.index - b.index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.