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

相关推荐
星依网络9 小时前
使用LabelImg工具标注数据(游戏辅助脚本开发)
python·游戏引擎·图形渲染·骨骼绑定
AT~10 小时前
unity 使用Socket和protobuf实现网络连接
unity·游戏引擎
speedoooo12 小时前
未来的App不再需要菜单栏?
前端·ui·容器·小程序·web app
weixin_4462608512 小时前
shadcn/ui - 打造个性化组件库的利器
ui
测试老哥13 小时前
UI自动化测试—Jenkins配置优化
自动化测试·软件测试·python·测试工具·ui·jenkins·测试用例
serve the people14 小时前
简化版滑块验证(仅 X 轴滑动 + 美化 UI)
ui
feiduoge15 小时前
教程 36 - 方向光照
windows·游戏引擎·图形渲染
百锦再15 小时前
与AI沟通的正确方式——AI提示词:原理、策略与精通之道
android·java·开发语言·人工智能·python·ui·uni-app
Just_Paranoid16 小时前
【Android UI】Android Tint 用法指南
android·ui·tint·porterduff·colorfilter
怣疯knight17 小时前
Cocos creator判断节点是否能用的方法
unity·cocos2d