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

相关推荐
郝学胜-神的一滴3 小时前
游戏设计、原型与开发 26:四种循环
开发语言·数据结构·游戏·游戏引擎·游戏策划
两水先木示3 小时前
【Unity】刮刮乐案例-RenderTexture实现思路
unity·游戏引擎
学术小李12 小时前
用虚幻引擎(UE)打开Obj模型
游戏引擎·虚幻
zhongben_keji12 小时前
APP WebView 混合开发体系:通信协议、加载优化与安全治理的工程落地
ui·ci/cd·自动化
张不无-Unity13 小时前
Unity的四种灯光Directional、Point、Spot 和 Area
unity·游戏引擎
fatCatLA13 小时前
UI模拟器使用手册
单片机·嵌入式硬件·ui
蓝悦无人机15 小时前
Figma组件库搭建教程(实战篇)
前端·ui·figma
zhongben_keji16 小时前
APP 无障碍与适老化改造工程实践:语义、视觉、交互三层落地
ui·ci/cd·自动化
汉得数字平台2 天前
【汉得飞码】构建接口与UI自动化测试全链路,让验证反馈持续驱动交付
自动化测试·人工智能·ui
淡海水2 天前
02-02-原理篇-Scriban模板引擎原理深度解析
unity·excel·游戏开发·luban