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

相关推荐
JIes__1 天前
Unity(二)——MonoBehavior中的重要内容
unity·游戏引擎
万物得其道者成1 天前
UI UX Pro Max: AI 驱动的设计系统生成引擎深度解析
人工智能·ui·ux
孟无岐1 天前
【Laya】LocalStorage 本地存储
typescript·游戏引擎·游戏程序·laya
妙为2 天前
unreal engine5角色把敌人 “挤飞”
游戏引擎·虚幻·ue·unrealengine5
4Forsee2 天前
【增强现实】快速上手 Vuforia Unity Android AR 应用开发
android·unity·ar
两水先木示2 天前
【Unity】对指定物体进行描边——模板测试法
unity·游戏引擎·shader·外描边
Miss_SQ2 天前
实现Unity录音、百度云语音转文字
unity·语音识别
CreasyChan2 天前
unity 对象池实测可用
unity·c#
weixin_424294672 天前
Unity项目的Artifacts文件夹过大怎么解决?
unity·游戏引擎
工业HMI实战笔记2 天前
汽车制造业HMI设计特点:高节拍生产的界面优化
ui·信息可视化·性能优化·自动化·汽车·交互