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

相关推荐
阿松爱学习8 小时前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
刘科领8 小时前
使用ollama & openweb-ui 本地搭建自己的AI
人工智能·python·ui·ai
淡海水10 小时前
02-04-原理篇-GC Roots与对象图遍历
算法·unity·c#·图·gc·遍历·roots
xy345317 小时前
Axure 9.0 动态面板基本操作
前端·ui·html·axure·原型·产品设计
霍格沃兹测试学院-小舟畅学21 小时前
UI 智能遍历测试:状态识别、路径规划与覆盖率评估
microsoft·ui
Pocker_Spades_A1 天前
Penpot自托管设计协作:Docker部署、MCP接入与Codex生成UI实操记录
ui·docker·容器
兰亭妙微UI设计公司2 天前
兰亭妙微界面设计公司分享:如何高效改善设计质量|实战分析
ui
且随疾风前行.2 天前
UI核心 - 绘制流程(测量、布局、绘制)
ui·dubbo
ndsc_d2 天前
2026年有哪些好用的AI UI设计工具?主流工具功能和适用场景对比
前端·人工智能·ui·ai·设计师·ai ui·ai ui工具
DM今天肝到几点?2 天前
OpenAI 向全量用户开放 GPT-6 与 Intelligent UI:聊天框正在变成工作台
gpt·ui·chatgpt