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

相关推荐
郝学胜-神的一滴1 小时前
中级OpenGL教程 007:解决背面光照异常高光问题
c++·unity·游戏引擎·three.js·opengl·unreal
RReality1 小时前
【Unity Shader URP】水面效果 实战教程
unity·游戏引擎·图形渲染
游乐码2 小时前
c#基础(七)延迟函数
开发语言·unity·c#·游戏引擎
LONGZETECH2 小时前
Unity 3D+C/S架构无人机数字孪生实训室:破解实训“三高”难题的底层技术实现
c语言·开发语言·3d·unity·架构·无人机
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_16:(深入掌握背景与边框的艺术)
前端·css·ui·html·tensorflow
万岳科技系统开发12 小时前
外卖系统小程序开发趋势:即时零售与同城配送的融合升级
unity·游戏引擎·零售
十贺16 小时前
【Unity开发字典】分包、黏包基本概念和处理逻辑实现
unity·游戏引擎
淡海水20 小时前
01-认知篇-总览-HybridCLR是什么
unity·c#·aot·热更新·clr·hybrid
lazy熊21 小时前
AI编程实战9:用 Codex 把一段重复 UI 抽成组件
ui·ai编程
c++之路21 小时前
状态模式(State Pattern)
ui·状态模式