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

相关推荐
星辰即远方10 小时前
计算器仿写总结
学习·ui·ios·cocoa·xcode
xcLeigh16 小时前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程
飞凌嵌入式21 小时前
告别多端重复开发:Buildroot+Flutter实现全平台UI风格统一
flutter·ui
DaLiangChen2 天前
Vuforia 地面识别案例
unity·ar
FungLeo2 天前
Flutter 把第三方 UI 库渐进迁回 Material 3:组件映射总表 + 四批次替换实战
flutter·ui
鹤卿1232 天前
「iOS」天气预报仿写总结
ui·ios·objective-c
江畔柳前堤2 天前
YOLO 目标检测全流程深度剖析
人工智能·yolo·目标检测·计算机视觉·unity·面试·vllm
A24207349302 天前
Vue + TypeScript 请求数据后结合 Element UI 实现树形菜单与下拉选择
vue.js·ui·typescript
头茬韭菜2 天前
5.5 权限交互:渐进式信任的 UI 设计
ui·交互