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

相关推荐
淡海水19 小时前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
FFFFujige21 小时前
【Unity】基于Dots + Luban的Buff模块
unity·游戏引擎
紫龙大侠1 天前
Unity许可证文件(激活成功后)默认保存位置
unity
且随疾风前行.1 天前
Paint Cavans高级绘制:[一]Paint画笔高级应用
android·ui
唯鹿1 天前
AI生成UI代码实践(二)—— Figba 更新月记
ui·ai·figma·1024程序员节·蓝湖
fqbqrr1 天前
2610C++,UI复合技术在窗口中绘画字体图标
c++·ui
Msir_Modern1 天前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
Oiiouui1 天前
Godot-GridGame架构逻辑层与实体/物品层篇
架构·游戏引擎·godot
天天进步20151 天前
Unity 2020.3 反复提示安全模式:一次 CS0009 与 DLL 文件占用的排查记录
unity·1024程序员节
true...1 天前
虚幻还原默认视角
游戏引擎·虚幻