【Unity3D】微信小游戏适配安全区域或胶囊控件(圆圈按钮)水平高度一致方案

面板保持如下RectTransform数据配置,挂上脚本,然后其子UI都要向上对齐,即

如下脚本是控制将面板的上边界与胶囊控件(圆心设置按钮)上边界水平对齐。

var topSize = rect.top; 这一行代码是获取到胶囊控件上边界,改为其他的就可以与其他位置水平对齐。

例如: var topSize = rect.bottom; 与胶囊控件下边界对齐

例如: var topSize = _sInfo.safeArea.top; 与安全区域上边界对齐(刘海屏下边界)

... ...

cs 复制代码
using System;
using Newtonsoft.Json;
using UnityEngine;
using WeChatWASM;

public class TopPanelAdapt : MonoBehaviour
{
    //开发阶段自定义posY
    public float posY = 0f;
    
    void Start()
    {
    //微信宏(具体项目可能不同)
#if UNITY_WEBGL || WEIXINMINIGAME || UNITY_EDITOR
        InitTop();
#endif
    }

    void InitTop()
    {
        var top_panel = GetComponent<RectTransform>();
        //胶囊控件区域信息
        var rect = WX.GetMenuButtonBoundingClientRect();
        //屏幕信息
        var _sInfo = WeChatWASM.WX.GetWindowInfo();
        if (rect != null && _sInfo != null)
        {
            var sHeight = _sInfo.windowHeight;
            top_panel.sizeDelta = Vector2.zero;
            
            var topSize = rect.top;
            //开发分辨率: 750 x 1334 (具体项目可能不同)
            //垂直px to rpx操作 从微信获取的是px像素尺寸 需转为Unity的rpx尺寸
            float newSize = (float)topSize * (1334f / UnityEngine.Screen.height);
            //PS: 如果是水平px 则是  px * (750f / UnityEngine.Screen.width);
            topSize = newSize;

            double t = 0;
            if (topSize > 0)
            {
                t = topSize / sHeight;
            }

            top_panel.pivot = new Vector2(0.5f, 0.5f);
            top_panel.anchorMin = new Vector2(0, 0);
            top_panel.anchorMax = new Vector2(1, 1 - (float)t);
        }
        else
        {
            top_panel.offsetMax = new Vector2(top_panel.offsetMax.x, -posY);
        }
    }
}
相关推荐
我的offer在哪里15 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
淡海水18 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景18 小时前
4.6 显存和缓存
unity
Zik----21 小时前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景1 天前
4.5 顶点和片元
unity
在路上看风景2 天前
31. Unity 异步加载的底层细节
unity
天人合一peng2 天前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂2 天前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的2 天前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y2 天前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表