【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);
        }
    }
}
相关推荐
LONGZETECH2 小时前
新能源汽车充电设备装配与调试仿真教学软件 技术架构与核心实现解析
大数据·算法·3d·unity·架构·汽车
丁小未3 小时前
Unity 几种常见合批手段的要求
游戏·unity·合批·srpbatcher·动态合批·静态合批
旧物有情1 天前
游戏开发常用架构 #MVP,MVC
游戏·unity·架构·mvc
勇踏前人未索之境1 天前
Unity打包运行于鸿蒙手机
unity·智能手机·harmonyos
玖玥拾1 天前
Unity 3D 笔记(十一)UI 框架进阶:栈弹窗交互、BasePanel 基类虚方法、DoTween 界面动画
笔记·3d·unity
郝学胜-神的一滴1 天前
中级OpenGL教程 023:Assimp模型加载全解——从源码到架构的骈文探秘
c++·unity·游戏引擎·cmake·unreal engine·opengl
xcLeigh2 天前
Unity基础:GameObject与Component——Unity核心架构思想彻底理解
unity·教程·component·gameobject
郝学胜-神的一滴2 天前
中级OpenGL教程 022:探秘三维世界的血脉传承——物体父子关系与矩阵递归奥义
c++·线性代数·unity·矩阵·游戏引擎·unreal engine·opengl
weixin_424294673 天前
Unity的测试Edit Mode和Play Mode,有什么区别?
unity