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

相关推荐
~远在太平洋~2 小时前
06-鸿蒙系统 uitest UI 自动化指南
ui·自动化·harmonyos
兰亭妙微UI设计公司3 小时前
兰亭妙微QT界面开发:设计系统侧边导航组件:告别混乱,实现高效协同
ui
点心的游戏开发世界3 小时前
GDScript 入门笔记(二):变量与数据类型
笔记·游戏引擎·godot
一梭键盘任平生4 小时前
Shader入门笔记2
unity
点心的游戏开发世界11 小时前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
点心的游戏开发世界13 小时前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
我命由我1234518 小时前
Photoshop - Photoshop 把两个 PSD 文件合并
学习·ui·职场和发展·产品运营·产品经理·学习方法·photoshop
郝学胜-神的一滴1 天前
CMake 047:解锁安装阶段自定义操作,告别配置阶段提前执行坑
运维·服务器·c++·游戏引擎·图形渲染·opengl
李游Leo1 天前
【共创稿事节】 HarmonyOS 7 空间化 UI 实战:从平面布局到空间层级的界面重构
ui·平面·harmonyos
图扑可视化2 天前
统一 DataModel 底座,HT UI 组件万物同源|中篇・运笔
ui·数字孪生·组件