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

相关推荐
点心的游戏开发世界27 分钟前
GDScript 入门笔记(十六):文件读写与数据持久化
开发语言·笔记·游戏引擎·godot
图扑软件1 小时前
下篇・换墨|主题/多语言/移动端,一套组件全覆盖
前端·javascript·ui·性能优化·数据可视化
点心的游戏开发世界1 小时前
GDScript 入门笔记(十三):字符串操作
开发语言·笔记·游戏引擎·godot
点心的游戏开发世界2 小时前
GDScript 入门笔记(十二):类型系统进阶
笔记·游戏引擎·godot
玖玥拾2 小时前
Lua 基础语法(三) 元表 metatable、元方法、模拟面向对象
开发语言·unity·lua
点心的游戏开发世界13 小时前
GDScript 入门笔记(十一):Lambda 与匿名函数
开发语言·笔记·游戏引擎·godot
公爵爱学习1 天前
无人机多点巡航
游戏引擎·无人机·cocos2d
公爵爱学习1 天前
关于无人机定点飞行的一些解释和Matlab程序绘制
游戏引擎·无人机·cocos2d
object not found2 天前
从 Page Design 到 System Design:我对 UI/UX 的一次认知变化
ui·ux
wgslucky2 天前
Godot GDScript初学者遇到的问题记录
游戏引擎·godot