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

相关推荐
lkbhua莱克瓦244 小时前
Zoggin 个人词汇认知实验室 — 业务需求文档(BRD V3.0)液态玻璃 UI × CEP 记忆引擎 × 认知增强飞轮
ui
jf加菲猫5 小时前
第15章 文件和目录
开发语言·c++·qt·ui
ZC跨境爬虫8 小时前
UI前端美化技能提升日志day8:(Watch专区字体优化+尺寸校准+视觉重构+结构分层)
前端·ui·重构·html
XiaoZhangGOGOGO9 小时前
《剑来2》动画第二季点映百度网盘提取码_百度网盘提取码资源
unity
早起傻一天~G9 小时前
vue2+element-UI表单封装
前端·vue.js·ui
惊鸿醉10 小时前
基于Kinect SDK的Unity艺术交互展项——完整技术方案
unity
报错小能手10 小时前
Swift UI 用 MVVM 架构 Combine EventBus 实现待办清单
开发语言·ui·swift
MFXWW212 小时前
从 Python 到 3D 开发:Ursina 引擎零基础入门学习路径与核心开发思路
python·游戏引擎·游戏程序·ursina
EaseUI20 小时前
【Ease UI】2026-04-24 项目更新:增加多种风格登录页,增加菜单风格切换
ui
mxwin1 天前
Unity URP 半透明阴影的局限性
unity·游戏引擎