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

相关推荐
钛态6 小时前
Flutter for OpenHarmony 实战:flex_color_scheme 打造极致鸿蒙美学 UI
flutter·ui·harmonyos
rhett. li8 小时前
FreeBSD系统中使用clang/clang++编译Skia源码的方法
c++·ui·用户界面
优选资源分享9 小时前
Seelen UI v2.5.0 丨 Win10/11 桌面定制工具
ui·实用工具
sdff113969 小时前
【HarmonyOS】Flutter适配鸿蒙多屏异构UI开发实战指南
flutter·ui·harmonyos
钛态12 小时前
Flutter for OpenHarmony 实战:Stack Trace — 异步堆栈调试专家
android·flutter·ui·华为·架构·harmonyos
郁闷的网纹蟒12 小时前
虚幻5---第16部分---敌人(中)
开发语言·c++·ue5·游戏引擎·虚幻
rhett. li12 小时前
Windows系统中使用MinGW-W64(gcc/g++或LLVM)编译Skia源码的方法
c++·windows·ui·用户界面
钛态12 小时前
Flutter for OpenHarmony 实战:YAML — 结构化配置解析专家
flutter·ui·华为·架构·harmonyos
爱搞虚幻的阿恺13 小时前
Niagara粒子系统-超炫酷的闪电特效(第一期 粒子的朝向与对齐)
游戏·ue5·游戏引擎·虚幻