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的简单实现

相关推荐
HwJack206 小时前
HarmonyOS APP UI单位适配深度实践:vp/fp/px的工程化解决方案分享
ui·华为·harmonyos
工业HMI实战笔记8 小时前
工业HMI色彩规范:4个禁忌+3类场景配色方案
ui·性能优化·自动化·汽车·交互
淡海水17 小时前
【节点】[ScleraLimbalRing节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·ring·limbal·sclera
csdn_life1820 小时前
Qwen3.5-397B-A17B-GGUF(UD-Q4_K_XL)3卡全流程部署文档(基础→API→UI)
ui
工控小龙人20 小时前
环保设备HMI:废气处理的浓度监控界面
ui·人机交互·用户界面
疯狂敲代码的老刘21 小时前
如何在 TRAE 中安装 UI/UX Pro Max Skill?完整图文教程
ui·ux·trae·skills
ellis197021 小时前
Unity特殊目录小结
unity
我命由我123451 天前
Photoshop - Photoshop 工具栏(63)注释工具
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
键盘鼓手苏苏1 天前
Flutter for OpenHarmony:markdown 纯 Dart 解析引擎(将文本转化为结构化 HTML/UI) 深度解析与鸿蒙适配指南
前端·网络·算法·flutter·ui·html·harmonyos