Unity 左右折叠显示与隐藏UI的简单实现

要实现一个简单的UI左右折叠显示与隐藏,可以结合遮罩,通过代码控制UI区块的宽度和位移来实现。

具体可以按以下步骤实现:

1、新建一个Image组件,并添加精灵,调整大小后,复制一份作为该UI的父物体,然后在该父物体上添加Mask组件,并勾掉Show Mask Graphic选项,如图:

2、新建两个控制按钮,如下图:

3、编写控制脚本:

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

public class SlideInOutUI : MonoBehaviour
{
    public RectTransform uiPanel;
    public Button showButton;
    public Button hideButton;
    public float slideSpeed = 5f;
    private bool isPanelShown = true;

    // Start is called before the first frame update
    void Start()
    {
        showButton.onClick.AddListener(ShowPanel);
        hideButton.onClick.AddListener(HidePanel);
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 targetPosition = isPanelShown ? Vector2.zero : new Vector2(-uiPanel.rect.width, 0);
        uiPanel.anchoredPosition = Vector2.Lerp(uiPanel.anchoredPosition, targetPosition, Time.deltaTime * slideSpeed);
    }

    private void ShowPanel()
    {
        isPanelShown = true;
    }

    private void HidePanel()
    {
        isPanelShown = false;
    }
}

4、运行效果:

Unity 左右折叠显示与隐藏UI的简单实现

相关推荐
Htht1112 小时前
【Qt】之【Bug】点击按钮(ui->pushButton)触发非本类设置的槽函数
qt·ui·bug
蔗理苦2 小时前
2025-05-07 Unity 网络基础7——TCP异步通信
网络·tcp/ip·unity·异步通信
FAREWELL000753 小时前
Unity基础学习(十)Camera组件
学习·unity·c#·游戏引擎
LouSean11 小时前
Unity按钮事件冒泡
经验分享·笔记·学习·unity·游戏引擎
VTheShow11 小时前
Unity Gizmos
unity
CodeCraft Studio12 小时前
报表控件stimulsoft教程:使用 JoinType 关系参数创建仪表盘
前端·ui
白熊18816 小时前
【图像大模型】Stable Diffusion Web UI:深度解析与实战指南
ui·stable diffusion
OJAC近屿智能18 小时前
英伟达发布Llama-Nemotron系列新模型,性能超越DeepSeek-R1
大数据·人工智能·ui·aigc·llama
虾球xz20 小时前
游戏引擎学习第264天:将按钮添加到分析器
c++·学习·游戏引擎
虾球xz1 天前
游戏引擎学习第266天:添加顶部时钟概览视图。
数据库·c++·学习·游戏引擎