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

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

相关推荐
幻世界26 分钟前
【Unity智能模型系列】Unity + MediaPipe + Sentis + ArcFace模型:构建高效人脸识别比对系统
unity·游戏引擎
军训猫猫头2 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
漫游者Nova8 小时前
虚幻引擎Unreal Engine5恐怖游戏设计制作教程,从入门到精通从零开始完整项目开发实战详细讲解中英字幕
ue5·游戏引擎·虚幻·游戏开发完整教程·恐怖游戏开发
死也不注释17 小时前
【Unity 编辑器工具开发:GUILayout 与 EditorGUILayout 对比分析】
unity·编辑器·游戏引擎
葬歌倾城18 小时前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue20 小时前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王20 小时前
hello判断
开发语言·c#
金增辉1 天前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
future14121 天前
C#学习日记
开发语言·学习·c#
傻啦嘿哟1 天前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#