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

相关推荐
jz_ddk19 小时前
[LVGL] 从0开始,学LVGL:基础构建篇 - 掌握UI的核心构建块
linux·网络协议·ui·rpc·嵌入式·gui·lvgl
Rhys..19 小时前
python自动化中(包括UI自动化和API自动化)env的作用和使用
python·ui·自动化
尤老师FPGA1 天前
使用ZYNQ芯片和LVGL框架实现用户高刷新UI设计系列教程(第三十二讲)
android·java·ui
三掌柜6661 天前
突破AR视觉交互边界:Unity赋能Rokid AR眼镜实现高精度图像识别与实时跟踪
unity·ar·交互
Larry_Yanan1 天前
QML学习笔记(三十四)QML的GroupBox、RadioButton
c++·笔记·qt·学习·ui
Brianna Home2 天前
Godot4.3开发2D游戏全记录
游戏·游戏引擎·godot·游戏程序·动画
王维志2 天前
使用Asp.Net WebApi(.net 8)托管Unity WebGL
unity·游戏引擎·webgl
开发游戏的老王2 天前
虚幻引擎入门教程:虚幻引擎的安装
游戏引擎·虚幻
muyouking112 天前
Unreal Engine 中的旋转表示:FQuat 与 FRotator 全面解析
游戏引擎·虚幻
打码的猿2 天前
在Qt中实现SwitchButton(开关按钮)
开发语言·qt·ui