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

相关推荐
weixin_4242946719 小时前
在Unity中,摄像机移动时出现“残影”或“闪烁”是常见问题,主要原因和处理方法。
unity·游戏引擎
孟无岐19 小时前
【Laya】Browser 使用说明
typescript·游戏引擎·游戏程序·laya
天人合一peng19 小时前
unity 3d 通过游戏对象的名子查到其对象
游戏·unity·游戏引擎
纯属个人爱好21 小时前
Unity2020+PicoNeo3Pro开发
unity·vr
__water1 天前
RHK《Unity接入DeepSeek问答》
unity·游戏引擎·智能问答·deepseek接入·deepseekapikey
小雨下雨的雨1 天前
Flutter 框架跨平台鸿蒙开发 —— Center 控件之完美居中之道
flutter·ui·华为·harmonyos·鸿蒙
小小工匠1 天前
LLM - A2UI:Google 引领的生成式 UI 革命
ui·a2ui
康de哥1 天前
MCP Unity + Claude Code 配置关键步骤
unity·mcp·claude code
小雨下雨的雨1 天前
Flutter 框架跨平台鸿蒙开发 —— Placeholder 控件之布局雏形美学
flutter·ui·华为·harmonyos·鸿蒙系统
美团骑手阿豪1 天前
Unity3D大规模点击检测:GPU Picking vs MeshCollider + Raycast
unity