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

相关推荐
BrightMZM1 小时前
记录一下Unity的BUG,Trial Version
unity·bug·打包·trial
Larry_Yanan2 小时前
QML学习笔记(三十一)QML的Flow定位器
java·前端·javascript·笔记·qt·学习·ui
Larry_Yanan3 小时前
QML学习笔记(三十)QML的布局器(Layouts)
c++·笔记·qt·学习·ui
▍ 小太阳 ☼3 小时前
Unity2022Navigation系统打开方式
unity·游戏引擎
qq_170264757 小时前
unity升级对ab变更的影响
unity·游戏引擎
KC_617 小时前
MySQL索引失效的十大场景与性能优化实战
ui
AA陈超8 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-04 使用效果应用游戏标签
c++·游戏·ue5·游戏引擎·虚幻
不伤欣9 小时前
Unity Mask镂空效果(常用于新手引导或高亮显示UI元素)
游戏·ui·unity·游戏引擎
偶尔的鼠标人18 小时前
Avalonia中,使用DataTable类型作为DataGrid的ItemSource 数据源
ui·c#·avalonia
左手吻左脸。19 小时前
Element UI表格中根据数值动态设置字体颜色
vue.js·ui·elementui