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

相关推荐
Howrun77710 小时前
虚幻引擎_控制角色移动的三种方法
游戏引擎·虚幻
航Hang*11 小时前
Photoshop 图形与图像处理技术——第9章:实践训练6——滤镜特效
图像处理·笔记·学习·ui·photoshop
小雨下雨的雨12 小时前
鸿蒙PC应用:工程结构解析与配置文件详解
ui·华为·harmonyos·鸿蒙系统
速冻鱼Kiel12 小时前
GASP笔记01
笔记·ue5·游戏引擎·虚幻
世人万千丶12 小时前
鸿蒙跨端框架 Flutter 学习 Day 3:性能进阶——Iterable 延迟加载与计算流的智慧
学习·flutter·ui·华为·harmonyos·鸿蒙·鸿蒙系统
孟无岐13 小时前
【Laya】Animator2D 使用指南
typescript·游戏引擎·游戏程序·laya
航Hang*13 小时前
Photoshop 图形与图像处理技术——第9章:实践训练4——图层和蒙版
图像处理·笔记·ui·photoshop·期末·复习
世人万千丶14 小时前
鸿蒙跨端框架 Flutter 学习 Day 3:工程实践——数据模型化:从黑盒 Map 走向强类型 Class
学习·flutter·ui·华为·harmonyos·鸿蒙·鸿蒙系统
航Hang*14 小时前
Photoshop 图形与图像处理技术——第9章:实践训练3——图像修饰和色彩色调的调整
图像处理·笔记·学习·ui·photoshop·期末
速冻鱼Kiel14 小时前
GASP笔记02
笔记·ue5·游戏引擎·虚幻