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

相关推荐
立刀人1 小时前
关于Unity 轴心点 Pivot、锚点 Anchor和控制轴
unity·游戏引擎
jf加菲猫4 小时前
第1章 认识Qt
开发语言·c++·qt·ui
Hody9120 小时前
【XR开发系列】Unity第一印象:编辑器界面功能布局介绍(六大功能区域介绍)
unity·编辑器·xr
q***7481 天前
私有化部署DeepSeek并SpringBoot集成使用(附UI界面使用教程-支持语音、图片)
spring boot·后端·ui
lrh30251 天前
Custom SRP - 14 Multiple Cameras
unity·渲染管线·srp
paopao_wu1 天前
DeepSeek-OCR实战(03):本地部署+简单UI测试
ui·ocr
lpfasd1232 天前
Valdi:Snapchat 开源的新一代跨平台 UI 框架
ui·开源
九章云极AladdinEdu2 天前
项目分享|告别枯燥命令行,构建终端用户界面的 TypeScript 库
javascript·ui·typescript
AA陈超2 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-11 实现自动运行
c++·游戏·ue5·游戏引擎·虚幻
Hi202402172 天前
为QML程序添加启动Logo:提升用户体验
windows·qt·ui·人机交互·qml·启动logo