用代码设置UGUI渲染无非和三个API有关:
1.SetAsFirstSibling();
2.SetAsLastSibling();
3.SetSiblingIndex(n)
SetAsFirstSibling()是设置为最先渲染的,即会被后渲染的挡住。
SetAsLastSibling();是设置为最后渲染的,即会挡住比他先渲染的
SetSiblingIndex(n)是设置层级,从0开始到childcount -1
当n为0时,其效果与SetAsFirstSibling();相同
但是当层级小于0时,其效果与SetAsLastSibling()一致
当层级为大于等于transform.parent.childCount - 1时,其效果与SetAsLastSibling一致
例子:
给蓝色Image挂上如下脚本
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.EventSystems;public class Test : MonoBehaviour, IPointerClickHandler{ int cnt = 0; public void OnPointerClick(PointerEventData eventData) { if (Input.GetKey(KeyCode.F)) { transform.SetAsFirstSibling(); } else if(Input.GetKey(KeyCode.L)) { transform.SetAsLastSibling(); } //transform.SetSiblingIndex(cnt++); }}
点击蓝色Image并按下F,发现image3(蓝色)跑到了Image(1)上面,
即蓝色Image的渲染层级变成0,最先渲染