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 小时前
OctreeNode
unity·c#·八叉树
WarPigs6 小时前
Unity协程返回值的解决方案
unity·游戏引擎
Ln5x9qZC28 小时前
Asp.Net MVC杂谈之:—步步打造表单验证框架[重排版](1)
ui
fe7tQnVan8 小时前
三大 Agent-UI 协议深度剖析:AG-UI、A2UI 与 MCP-UI 的设计哲学与工程实践
ui·状态模式·命令模式
LcGero9 小时前
Lua + Cocos Creator 实战:用 Lua 驱动 UI 与游戏逻辑
游戏·ui·lua
ZC跨境爬虫9 小时前
Playwright进阶操作:鼠标拖拽与各类点击实战(含自定义拖拽实例)
前端·爬虫·python·ui
DYuW5gBmH9 小时前
如何一步步将 ASP.NET MVC 升级为.NET
ui
for_ever_love__10 小时前
Objective-C学习:UI的初步了解
学习·ui·objective-c
小灰灰搞电子10 小时前
Qt UI 线程详解-阻塞与解决方案
开发语言·qt·ui
spencer_tseng10 小时前
UI 2026.03.26
ui