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

相关推荐
_ZHOURUI_H_2 分钟前
Unity EasyECS:并不是所有字段都适合 SoA,Unity 项目中应该怎样拆数据
游戏·unity·性能优化·架构·游戏引擎
TO_ZRG2 小时前
Unity 编辑器之 SettingsProvider、Hierarchy、Project、SearchField
java·unity·编辑器
yj爆裂鼓手11 小时前
spine绑定骨骼运动工具&spine纹理压缩自动设置工具
游戏·unity
mqiqe12 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
qq_4260039613 小时前
【UI自动化测试】UI自动化报错解决方案
运维·ui·自动化
Oll Correct13 小时前
Adobe illustrator 案例九:百宝箱图标绘制
笔记·ui·adobe·illustrator
惊鸿醉14 小时前
Unity 实战:用讯飞 WebAPI 做一个“说普通话、播方言“的语音程序
unity·c#·游戏引擎·语音识别
略略略咯咯15 小时前
C#Unity
开发语言·unity·c#
小贺儿开发21 小时前
Unity 局域网遥控幻灯片展示工具 1.0
unity·网络通信·工具·ppt·控制·网页·互动
xy345321 小时前
Axure 9.0 条形图绘制超详细教程:静态展示
ui·产品经理·axure·条形图