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 小时前
AI在生产制造企业的六大成熟落地场景(可量产、可验收、非噱头)
大数据·ui·前端开发
五仁烧饼2 小时前
Unity性能优化系列内存篇 - 移动端内存优化
unity·性能优化·游戏引擎
CoderIsArt1 天前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
WiChP2 天前
【V0.1B15】从零开始的2D游戏引擎开发之路
游戏引擎
TomEval2 天前
【Web UI 自动化】05 - KDT 模式原理与实现
前端·ui·自动化
简单Janeee2 天前
[Vue 3 从零到上线]-第九篇:更美更强——引入 UI 库与网络请求 (Axios)
网络·vue.js·ui
中国软件测试质量协会3 天前
奇林测试平台(kylinTOP)UI自动化测试能力深度解析
ui
greasyfork3 天前
Mac Sketch v2026.3 矢量图设计工具
macos·ui·sketch
zhchyun20083 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(06)
ui·unity·游戏引擎
中国软件测试质量协会3 天前
国产UI自动化测试工具的“技术代际“演进与自主可控之路
测试工具·ui·自动化