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

相关推荐
benben0442 小时前
Unity3D仿星露谷物语开发34之单击Drop项目
游戏·ui·unity·游戏引擎
妙为2 小时前
unreal engine5开发仿鬼泣5的游戏,把敌人击飞到空中4连击
游戏·游戏引擎·虚幻·仿鬼泣5·空中连击
虾球xz5 小时前
游戏引擎学习第205天
学习·游戏引擎
benben0447 小时前
Unity3D仿星露谷物语开发33之光标位置可视化
游戏·ui·unity·游戏引擎
张屿秋11 小时前
在Unity中,如果物体上的脚本丢失,可以通过编写一个自定义编辑器脚本来查找并删除这些丢失的组件
unity·编辑器·游戏引擎
ailinghao11 小时前
使用Cusor 生成 Figma UI 设计稿
ui·ai·figma
闪电麦坤951 天前
Unity:Simple Follow Camera(简单相机跟随)
unity·游戏引擎
湛谷Gooyuit1 天前
LVGL修改标签文本,GUI Guider的ui不生效
ui
baivfhpwxf20231 天前
WPF 免费UI 控件HandyControl
ui·wpf
一个程序员(●—●)1 天前
xLua环境控制+xLua的Lua调用C#的1
开发语言·unity·c#·lua