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

相关推荐
_Doubletful3 分钟前
从零开始学 UI 第一篇:Figma 快速上手实战指南(上)
ui·figma
mmsx1 小时前
Android 三类「看着无关」的故障:大事务、UI 阻塞与 ViewModel 作用域
android·ui
淡海水2 小时前
07-01-源码-.NET Core GC总览与架构
unity·架构·c#·.netcore·gc
民乐团扒谱机4 小时前
【超详细】从“硬编码”到“主题化宏”:大型桌面端UI重构与模块解耦实战避坑指南
ui·重构
true...5 小时前
虚幻里面设置物体显示、隐藏的两种方式
游戏引擎·虚幻
电子云与长程纠缠19 小时前
UE5魂系游戏开发教程05
开发语言·学习·游戏·ui·ue5
淡海水1 天前
06-03-源码-时间分片与调度策略
unity·c#·gc
特立独行的猫a1 天前
AI时代的应用开发神器:cj-tauri 已支持鸿蒙 PC,第一次的踩坑记录
ui·harmonyos·tauri·仓颉·鸿蒙pc·cj-tauri
郝学胜-神的一滴2 天前
游戏设计:原型与开发 08:我们到底在为谁做游戏
程序人生·游戏·游戏引擎·游戏开发·游戏策划
五仁烧饼2 天前
动手学 Shader Graph(二):溶解与边缘发光
游戏·unity·shader·shader graph