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();
    }
}

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

相关推荐
IT规划师11 分钟前
C#|.net core 基础 - 扩展数组添加删除性能最好的方法
c#·.netcore·数组
时光追逐者43 分钟前
分享6个.NET开源的AI和LLM相关项目框架
人工智能·microsoft·ai·c#·.net·.netcore
friklogff1 小时前
【C#生态园】提升C#开发效率:深入了解自然语言处理库与工具
开发语言·c#·区块链
仙魁XAN1 小时前
Unity 设计模式 之 创造型模式-【工厂方法模式】【抽象工厂模式】
unity·设计模式·工厂方法模式·抽象工厂模式
我要吐泡泡了哦3 小时前
GAMES104:15 游戏引擎的玩法系统基础-学习笔记
笔记·学习·游戏引擎
__water10 小时前
『功能项目』回调函数处理死亡【54】
c#·回调函数·unity引擎
__water10 小时前
『功能项目』眩晕图标显示【52】
c#·unity引擎·动画事件
__water10 小时前
『功能项目』第二职业法师的平A【57】
c#·unity引擎·魔法球伤害传递
躺下睡觉~12 小时前
Unity-Transform类-父子关系
java·unity·游戏引擎
躺下睡觉~12 小时前
Unity-Transform类-缩放和看向
unity·游戏引擎