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

相关推荐
相信神话20213 小时前
第四章:Godot 4.6 核心概念与开发环境搭建
游戏引擎·godot·2d游戏编程·godot4·2d游戏开发
代数狂人4 小时前
在Godot中应用面向对象原则:C#脚本实践
c#·游戏引擎·godot
计算机应用技术三班-欧婷6 小时前
ElementUI从入门到实战全攻略
前端·vue.js·ui
Sator16 小时前
Unity关于射击游戏人物动画的设计经验
游戏·unity·游戏引擎
冰凌糕6 小时前
Unity3D Shader 坐标空间详解
unity
Zik----7 小时前
Windows安装cuda
前端·ui·xhtml
心前阳光19 小时前
UI在指定区域内拖拽
ui·命令模式
love530love1 天前
冷门干货!llama.cpp 自带原生网页聊天 UI,无需第三方依赖一键开启
人工智能·windows·ui·llama·flash-attention·switch-cuda
风酥糖1 天前
Godot游戏练习01-第20节-增加亿点点细节
游戏·游戏引擎·godot
智算菩萨1 天前
【OpenGL】6 真实感光照渲染实战:Phong模型、材质系统与PBR基础
开发语言·python·游戏引擎·游戏程序·pygame·材质·opengl