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

相关推荐
张老师带你学4 小时前
Unity 机器人 humanoid +shader效果
科技·游戏·unity·游戏引擎·模型
Ulyanov4 小时前
《玩转QT Designer Studio:从设计到实战》 QT Designer Studio组件化开发与UI组件库构建
开发语言·python·qt·ui·雷达电子战系统仿真
鼎道开发者联盟8 小时前
鼎享会 | OpenClaw Control UI 前端架构全解析:自研 UI 对接 Server 实操指南
前端·ui·架构·openclaw·control ui
星河耀银海10 小时前
Unity基础:UI组件详解:Toggle开关的状态控制
ui·unity·lucene
mxwin10 小时前
Unity URP 法线贴图:世界空间 vs 切线空间 深度解析两种法线贴图格式在实时渲染中的核心差异、适用场景与性能权衡
unity·游戏引擎·贴图
ZC跨境爬虫11 小时前
UI前端美化技能提升日志day1:矢量图片规范与自适应控制栏实战
前端·css·ui·状态模式
ai_coder_ai11 小时前
自动化脚本ui编程之水平滚动布局(hscroll)
ui·autojs·自动化脚本·冰狐智能辅助·easyclick
ZC跨境爬虫11 小时前
UI前端美化技能提升日志day2:图片优化、字体本地化与设计美感解析
前端·javascript·ui·状态模式
南村群童欺我老无力.11 小时前
鸿蒙开发中的@Builder装饰器函数中的UI语法限制
ui·华为·harmonyos
qq_452396231 天前
第一篇:《UI自动化测试从零到一:为什么需要它?核心价值与挑战》
ui