Unity设置UI和Render的渲染层级

通过给UI或物体挂载下面脚本,来设置层级

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
namespace Common
{
    //设置UI和render的层级
    public class UIDepth : MonoBehaviour
    {
        public int order;
        public bool isUI = true;
        void Start()
        {
            UpdateOrder();
        }

        public void SetOrder(int order)
        {
            this.order = order;

        }

        private void UpdateOrder()
        {
            if (isUI)
            {
                Canvas canvas = GetComponent<Canvas>();
                if (canvas == null)
                {
                    canvas = gameObject.AddComponent<Canvas>();
                }
                canvas.overrideSorting = true;
                canvas.sortingOrder = order;
            }
            else
            {
                Renderer[] renders = GetComponentsInChildren<Renderer>();

                foreach (Renderer render in renders)
                {
                    render.sortingOrder = order;
                }
            }
        }
    }
}

 

posted @ 2024-05-22 09:44  weigang  阅读(199)  评论(0编辑  收藏  举报