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

相关推荐
B0URNE16 小时前
【Unity基础详解】(11)Unity核心:输入系统
unity·游戏引擎
小小8程序员17 小时前
C# XAML中x:Type的用法详解
开发语言·ui·c#
Aevget17 小时前
界面控件DevExpress WinForms中文教程:Data Grid - 如何获取汇总值?
ui·.net·界面控件·winform·devexpress
世洋Blog18 小时前
Unity开发微信小游戏-减少WASM包体大小
unity·游戏引擎·wasm·微信小游戏
TO_ZRG19 小时前
Unity 通过 NativePlugin 接入Android SDK 指南
android·unity·游戏引擎
jtymyxmz21 小时前
《Unity Shader》10.2.1 镜子效果
unity·游戏引擎
ellis197021 小时前
Unity打开新项目Package相关报错处理记录
unity
reddingtons1 天前
Illustrator 3D Mockup:零建模,矢量包装一键“上架”实拍
人工智能·ui·3d·aigc·illustrator·设计师·平面设计
言之。1 天前
AI时代的UI发展
人工智能·ui
微:xsooop1 天前
iOS 上架4.3a 审核4.3a 被拒4.3a 【灾难来袭】
flutter·unity·ios·uniapp