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

相关推荐
犹若故人归5 小时前
Android开发应用--高级UI界面设计
android·ui
一个学Java小白11 小时前
TUI的王者——ncurses.md
linux·ui
归真仙人12 小时前
【UE】UMG安卓相关问题
android·ue5·游戏引擎·ue4·虚幻·unreal engine
BuHuaX13 小时前
Unity项目怎么接入抖音小游戏?
unity·c#·游戏引擎·wasm·游戏策划
Sator114 小时前
unity Rayfire破碎插件的踩坑点
unity·游戏引擎
极客先躯15 小时前
基于 EasyUI 和 jQuery 封装的企业级日期时间选择器组件库,采用标准的 jQuery 插件开发规范,实现了高度模块化和可复用的 UI 组件
ui·jquery·日期选择器·时间选择器·easyui
kk哥889915 小时前
Android UI 优化指南:流畅度与体验双提升
android·ui
鱼蛋-Felix16 小时前
C#浮点数在部分国家解析失效问题
开发语言·unity·c#
_风华ts16 小时前
虚幻引擎碰撞相关的属性
游戏引擎·虚幻·collision
小雨下雨的雨16 小时前
Flutter鸿蒙共赢——像素的解构:沃罗诺伊点描与权重平衡的艺术
flutter·ui·华为·harmonyos·鸿蒙系统