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

相关推荐
Jiaberrr2 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Artistation Game1 天前
九、怪物行为逻辑
游戏·unity·游戏引擎
百里香酚兰1 天前
【AI学习笔记】基于Unity+DeepSeek开发的一些BUG记录&解决方案
人工智能·学习·unity·大模型·deepseek
妙为1 天前
unreal engine5制作动作类游戏时,我们使用刀剑等武器攻击怪物或敌方单位时,发现攻击特效、伤害等没有触发
游戏·游戏引擎·虚幻·碰撞预设
dangoxiba1 天前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
先生沉默先2 天前
使用Materialize制作unity的贴图,Materialize的简单教程,Materialize学习日志
学习·unity·贴图
神一样的老师2 天前
如何解决 Photoshop 中的“暂存盘已满”错误
ui·photoshop
十画_8242 天前
Visual Studio 小技巧记录
unity·visual studio
red_redemption2 天前
cpp,git,unity学习
git·unity·游戏引擎
tealcwu2 天前
【Unity踩坑】Unity更新Google Play结算库
unity·游戏引擎