Unity 控制组件显示在同级最前端或者最后端

有时候我们在做一些类似轮播的效果时,就通常会用到切换某张图片显示在最后端或者最前端。

如我写一个这样的脚本:

复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChangePic : MonoBehaviour
{
    public Transform tran;   
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(ChangeNextImage());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator ChangeNextImage()
    {        
        while (true)
        {
            yield return new WaitForSeconds(1f);
            tran.GetChild(0).SetAsLastSibling();
        }
    }
}

把它放到需要切换的组件里,可实现如下简单切换效果:
UI简单轮播切换_哔哩哔哩_bilibili

从上面案例看,方法是简单的:

首先获取组件的RectTransform组件,然后就可以调用SetAsLastSibling()和SetAsFirstSibling()方法。就可以把组件移动到最后面和最前面。

复制代码
using UnityEngine;
using UnityEngine.UI;

public class MoveToLastSibling : MonoBehaviour
{
    void Start()
    {
        // 获取组件的RectTransform
        RectTransform rectTransform = GetComponent<RectTransform>();

        // 将组件移动到最前面
        rectTransform.SetAsFirstSibling();

        // 将组件移动到最后面
        rectTransform.SetAsLastSibling();
    }
}

需要注意的是以上两个方法都是在当前父物体的同级组件之间进行移动。

相关推荐
jtymyxmz1 小时前
《Unity Shader》11.3.1 流动的河流
unity·游戏引擎
ironinfo2 小时前
C#性能优化随记
开发语言·性能优化·c#
小马过河R2 小时前
开发游戏需要哪些岗位和角色参与
游戏·游戏引擎·游戏程序
czhc11400756634 小时前
Winform121 prograssbar Imagelist panel
c#
我是苏苏4 小时前
C#基础:如何创建一个类库并且封装成DLL
开发语言·c#
Yuyang_Leo4 小时前
eventTime+watermarker+allowedLateness到底窗口关闭时间是什么?
c#·linq
jtymyxmz4 小时前
《Unity Shader》11.3.1 续 流动的水流的阴影
unity·游戏引擎
世洋Blog5 小时前
Unity性能优化-2d游戏的DrawCall
游戏·unity·面试·性能优化·游戏引擎
jtymyxmz5 小时前
《Unity Shader》11.2.2 滚动的背景
unity·游戏引擎