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

相关推荐
ellis19705 小时前
Unity资源管理框架Addressables[六] 内存管理
unity
派葛穆5 小时前
Unity-鼠标悬停改变物体层级
unity·游戏引擎
Swift社区8 小时前
ArkUI 如何设计 AI 原生 UI?
人工智能·ui
小贺儿开发9 小时前
Unity3D 爆炸图案例演示
unity·产品·urp·机械拆装·爆炸图·零件·效果设计
新缸中之脑12 小时前
Claude生成式UI的逆向与利用
ui
ayaya_mana1 天前
快速安装Nginx-UI:让Nginx管理可视化的高效方案
运维·nginx·ui
Yasin Chen1 天前
Unity TMP_SDF 分析(二)数据来源2
unity·游戏引擎
Mao_Hui1 天前
Unity3d实时读取Modbus RTU数据
开发语言·嵌入式硬件·unity·c#
相信神话20211 天前
《酒魂》游戏开发实战——从设计思想到 Godot 实现(单机完整版)
游戏引擎·godot
zzz84151 天前
Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)
spring boot·后端·ui