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

相关推荐
AllBlue5 小时前
unity嵌入安卓界面,如何显示状态
android·unity·游戏引擎
tealcwu6 小时前
【Unity技巧】实现在Play时自动保存当前场景
java·unity·游戏引擎
赵财猫._.6 小时前
【Flutter x 鸿蒙】第三篇:鸿蒙特色UI组件与Flutter的融合使用
flutter·ui·harmonyos
CodeCraft Studio6 小时前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建漏斗图
ui·c#·excel·aspose·excel开发·excel漏斗图·漏斗图
tealcwu6 小时前
【Unity基础】实现Scroll View跟随动态内容滚动
java·unity·游戏引擎
seven_7678230987 小时前
MateChat自然语言生成UI(NLG-UI):从描述到可交互界面的自动生成
ui·交互·devui·matechat
野奔在山外的猫7 小时前
【文档】VSCode 配置 Unity 环境流程
unity
crary,记忆8 小时前
如何理解 React的UI渲染
前端·react.js·ui·前端框架
xun_xin6668 小时前
QWidget for C++:ui资源使用
ui
技术小甜甜8 小时前
[Godot排错] 上传 Google Play Console 封闭测试时签名证书不匹配错误的解决方案
游戏引擎·godot·游戏开发