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

相关推荐
HH‘HH4 小时前
Unity 项目创建标准指南:分辨率、尺寸、文件路径与命名规范
unity·游戏引擎
条tiao条7 小时前
Navigation页面跳转教学博客
ui·华为·harmonyos·鸿蒙·页面跳转
元气少女小圆丶7 小时前
unity发布web嵌入到前端页面的接受参数
前端·unity·webgl
HH‘HH7 小时前
Unity 打包程序设置及注意事项全攻略
unity·游戏引擎
এ慕ོ冬℘゜10 小时前
前端实战:Textarea 实时字数计数输入器(带字数限制+UI优化完整源码)
前端·ui
fqbqrr10 小时前
2607d,parin游戏引擎
游戏引擎·d
qq_1702647511 小时前
unity里 Burst的用法
unity·游戏引擎
HH‘HH15 小时前
Unity 相机与光照调整:从基础到进阶的实战指南
unity
todoitbo15 小时前
让数据看板随时可见:Grafana + cpolar 远程访问实战
ui·网络安全·grafana·数据看板·远程访问
Liknana15 小时前
Qt 圆角表格控件实战:setMask + 抗锯齿描边 + 多层阴影
qt·ui