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

相关推荐
淡海水9 小时前
01-03-认知篇-基础-Excel配置工作流痛点深度分析
unity·架构·excel·游戏开发·luban
谙弆悕博士12 小时前
生物启发式集群(Swarm)工程实现:五条规则、一群蚂蚁和四十个粒子
人工智能·gpt·游戏引擎·cocos2d·蚁群算法·多智能体·boids
Frankie_stand1 天前
无人机售后故障处理全流程:从受理、SLA 时限到责任划分与改进闭环
游戏引擎·无人机·cocos2d
鲸渔2 天前
【AI Agent系列课程33-FastAPI 基础07】自动文档与接口调试:Swagger UI 和 ReDoc 入门
python·ui·fastapi·ai编程
敲上瘾5 天前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
zdr尽职尽责9 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
辰小忆10 天前
11 · RunCurveChart —— 实时运行曲线
c++·ui·duilib
ellis197011 天前
Claude Code[二] 上下文相关的机制
unity·ai编程
敲上瘾12 天前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
zdr尽职尽责12 天前
Unity 3C 动画系统:从「蜘蛛网」到可维护的动画架构
unity·架构·游戏引擎