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

相关推荐
EQ-雪梨蛋花汤16 分钟前
【AI工具】使用 Doubao-Seed-Code 优化 Unity 编辑器插件:从功能实现到界面美化的完整实践
人工智能·unity·编辑器
g***B7382 小时前
元宇宙游戏引擎
游戏引擎
Dr.勿忘4 小时前
开源Unity小框架:高效单例与模块化设计
游戏·unity·开源·c#·游戏引擎·游戏程序·gamejam
百锦再13 小时前
[特殊字符] HBuilder uni-app UI 组件库全方位对比
android·java·开发语言·ui·rust·uni-app·go
jtymyxmz2 天前
《Unity Shader》8.4 透明度混合
unity·游戏引擎
世洋Blog2 天前
利用<<左移运算符优雅的设计游戏能力的任意组合和判断
游戏·unity·c#
lqj_本人2 天前
鸿蒙与Qt的双线程模型:主线程与UI线程的博弈
qt·ui·harmonyos
南华2 天前
Visual Studio 2022 加载解决方案缓慢
ui
毛甘木2 天前
Unity MonoPInvokeCallback 使用教程
c++·unity
心疼你的一切2 天前
Unity开发Rokid应用之离线语音指令交互模型
android·开发语言·unity·游戏引擎·交互·lucene