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

相关推荐
虾球xz2 小时前
游戏引擎学习第119天
学习·游戏引擎
lovingyk6 小时前
Unity 脚本控制3D人物模型的BlendShape
unity
晴空了无痕10 小时前
现代任务调度系统架构深度解析——以TaskSchedulerController为核心的弹性任务管理方案
unity·系统架构·游戏引擎
虾球xz17 小时前
游戏引擎学习第118天
学习·游戏引擎
软件黑马王子18 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
小盼江1 天前
水果生鲜农产品推荐系统 协同过滤余弦函数推荐水果生鲜农产品 Springboot Vue Element-UI前后端分离 代码+开发文档+视频教程
vue.js·spring boot·ui
不吃斋的和尚1 天前
Unity中一个节点实现植物动态(Shader)
unity·游戏引擎
虾球xz1 天前
游戏引擎学习第117天
学习·游戏引擎
程序猿多布1 天前
Unity 位图字体
unity
千年奇葩1 天前
Unity shader glsl着色器特效之 模拟海面海浪效果
unity·游戏引擎·着色器