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

相关推荐
DaLiangChen5 小时前
Unity 实用工具:动态绘制物体边界包围盒(支持屏幕固定线宽)
unity·游戏引擎
张老师带你学6 小时前
Unity 食物 农产品相关
科技·游戏·unity·游戏引擎·模型
mxwin6 小时前
Unity Custom Interpolators与半透明阴影的原理与实战
unity·游戏引擎·shader
晴夏。6 小时前
UE5第三人称模板实现及相关引擎源码分析
unity·ue5·游戏引擎·ue
HAPPY酷6 小时前
解决 Unreal Engine 编译报错 MSB4018:三个核心排查方向
游戏引擎·虚幻
apollowing7 小时前
Avalonia UI 12.0.0 正式发布:架构演进和性能飞跃
ui·架构
oioihoii8 小时前
OpenClaw桌面 UI 自动化中的 Token 消耗问题几种可能的优化方向
运维·ui·自动化
qq_452396239 小时前
第九篇:《处理常见复杂UI组件:下拉框、弹窗、iframe、多窗口》
ui
深蓝海拓10 小时前
Qt:创建一套基于HSL颜色体系的颜色库
笔记·python·qt·学习·ui
for_ever_love__10 小时前
UI学习:反向传值(代理传值)深入学习
学习·ui·objective-c