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

相关推荐
LT10157974441 小时前
2026年UI自动化测试平台选型指南:全界面自动化覆盖方案
运维·ui·自动化
Java知识技术分享2 小时前
opencode安装ui-ux-pro-max和frontend-ui-ux技能
人工智能·ui·个人开发·ai编程·ux
auccy4 小时前
Unity Sprite 添加法线贴图
unity·贴图·normal
一锅炖出任易仙4 小时前
创梦汤锅学习日记day32
学习·ai·游戏引擎
里昆5 小时前
【illustrator】如何在illustrator中画箭头
ui·illustrator
Maimai108085 小时前
Web3 前端交易系统如何落地:从下单 UI 到 Operation 编码、签名与实时状态更新
前端·react.js·ui·架构·前端框架·web3
HarvestHarvest6 小时前
【Copy Web独立开发者实战:我是如何用 AI 实现网页 UI 1:1 完美复刻的?】
前端·人工智能·ui
狼哥16867 小时前
《新闻资讯》八、产品定制层实现指南
ui·华为·harmonyos
mxwin7 小时前
次世代角色 PBR 贴图制作 + Unity URP 接入 极简流程图
unity·流程图·贴图·shader
mxwin8 小时前
Unity URP 法线贴图如何生成 用什么工具创建
unity·游戏引擎·贴图