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

相关推荐
chillxiaohan1 小时前
unity粗糙、高光、光泽度调节shader记录
unity·游戏引擎
星夜泊客3 小时前
Unity UI 渲染与 Rebuild 机制简易解析
unity·游戏引擎
繁星流动 >_<4 小时前
axure点击图标放大展示
ui·axure
航Hang*4 小时前
Photoshop 图形与图像处理技术——第7章:滤镜的应用
图像处理·笔记·ui·photoshop
一线灵5 小时前
跨平台游戏引擎 Axmol-2.11.1 发布
游戏引擎
qiminixi14 小时前
Unity 6000下载
unity·unity 6000·unity 6000下载
航Hang*16 小时前
Photoshop 图形与图像处理技术——第8章:图像的色彩与色彩调整和图像的输出与优化
图像处理·笔记·ui·photoshop
聪明努力的积极向上17 小时前
【C#】线程解析:从“页面未响应”到彻底理解 .NET 中的 UI 线程、Task、Thread、COM 与消息泵
ui·.net
CreasyChan18 小时前
Unity Shader 入门指南
unity·c#·游戏引擎·shader
漂视数字孪生世界18 小时前
Unity团结引擎的前世今生
unity·游戏引擎·数字孪生