Unity 3D DevLog-WebGL

Unity3D WebGL开发问题汇总
—Neo He 2021/12/06
1.分辨率 IOS
Canvas Size 23881668
Canvas Scaler: 1.55
注意:Canvas Scaler从PC 1920
1080切换为IOS做适配时需要调整为1.55,如平台选择为IOS,则Canvas Scaler为1

当在嵌套容器中添加Unity WebGL页面时,需设置以下内容,如是原生浏览器,则无需设置(不明原理,测试所得):

Resolution and Presentation
Default Canvas width: 1194
Default Canvas height: 834

2.移动端取消浏览器警告
将此脚本置于工程中Editor文件夹下即可

public class CancelMobileBrowserWarnning
{
    [PostProcessBuild]
    public static void OnPostProcessBuild(BuildTarget target, string targetPath)
    {
        if (target != BuildTarget.WebGL) return;
        var path = Path.Combine(targetPath, "Build/UnityLoader.js");
        var text = File.ReadAllText(path);
        text = text.Replace("UnityLoader.SystemInfo.hasWebGL?UnityLoader.SystemInfo.mobile?", "t();/*UnityLoader.SystemInfo.hasWebGL?UnityLoader.SystemInfo.mobile?");
        text = text.Replace("e.popup(\"Your browser does not support WebGL\",[{text:\"OK\",callback:r}])", "e.popup(\"Your browser does not support WebGL\",[{text:\"OK\",callback:r}])*/");
        
        File.WriteAllText(path, text);
    }
}

以上文本是取消提醒相关代码,在某些WebTemplate中并非有相同文本结构,有修改时可能会导致错误,需手动检查,并重新修改通配符

2022/03/03 ADD

3.IOS WebGL Platform is UNITY_WebG

4.UI遮罩API相关

a.EventTrigger
public static bool isPointerOverUI;

        var trigger = GetComponent<EventTrigger>();
        if (trigger == null)
            trigger = gameObject.AddComponent<EventTrigger>();
        trigger.triggers = new List<EventTrigger.Entry>();
        EventTrigger.Entry enterEntry = new EventTrigger.Entry();
        enterEntry.eventID = EventTriggerType.PointerEnter;
        enterEntry.callback = new EventTrigger.TriggerEvent();
        UnityAction<BaseEventData> enterCallback = new UnityAction<BaseEventData>((data) =>
        {
            isPointerOverUI = true;
        });
        enterEntry.callback.AddListener(enterCallback);

为遮罩可能需添加的TriggerType有PointerEnter,PointerExit,PointerDown,PointerUp,PointerClick

b.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)
EventSystem.current.IsPointerOverGameObject()

c.GraphicRaycaster.Raycast
public class UIRaycaster : MonoBehaviour
{
    List<RaycastResult> raycastResults = new List<RaycastResult>();

    void Update()
    {
        if (Input.touchCount > 0)
        {
            GraphicRaycaster(Input.GetTouch(0).position);
        }
    }
    public EventSystem eventSystem;
    public GraphicRaycaster graphicRaycaster;
    public List<RaycastResult> GraphicRaycaster(Vector2 p_Positon)
    {
        var pointer = new PointerEventData(eventSystem);
        pointer.position = p_Positon;
        raycastResults.Clear();
        graphicRaycaster.Raycast(pointer, raycastResults);
        return raycastResults;
    }
}

5.替换WebGL Template

官方文档相关:
https://docs.unity3d.com/cn/2019.4/Manual/webgl-templates.html
解决方案Git地址:
https://github.com/greggman/better-unity-webgl-template

需要调整index以下内容,以避免在加载完成,进入Unity场景后,加载ICON与进度条仍显示

index.html

 function UnityProgress(gameInstance, progress) {
    if (!gameInstance.Module) {
      return;
    }
    const loader = document.querySelector("#loader");
    if (!gameInstance.progress) {
      const progress = document.querySelector("#loader .progress");
      progress.style.display = "block";
      gameInstance.progress = progress.querySelector(".full");
      loader.querySelector(".spinner").style.display = "none";
    }
    gameInstance.progress.style.transform = `scaleX(${progress})`;
    if (progress === 1 && !gameInstance.removeTimeout) {
      gameInstance.removeTimeout = setTimeout(function() {
          loader.style.display = "none";
      }, 2000);
    }
  }

将倒数第3行中的2000修改为一个较小值(100以下)
注意:在最终部署的终端上,如果有缓存,可能会显示Unity默认的WebGL Template,需清理缓存。

2021/12/30
2020以下版本WebGL打包设置
1.测试记录

Player Setting->
|->Other Setting
Strip Engine Code*|->Publish Setting
Enable Exceptions: Explicitly Thrown Exceptions Only
Compression Format:Gzip
压缩比:Brotli>Gzip>Disable
Data Caching ☑

2022/03/03
2020以上版本WebGL打包设置
2020.3.21f1c1版本WebGL打包及Addressable Assets System使用
1.打包

Player Setting->
Other Setting->
Rendering->Color Space ->Linear
Auto Graphics API □(未勾选状态将出现Graphics APIs选项)
以上文本是取消提醒相关代码,在某些WebTemplate中并非有相同文本结构,有修改时可能会导致错误,需手动检查,并重新修改通配符

2.Addressable Assets System
API
使用泛型异步加载方式进行资源加载

Addressables.LoadAssetsAsync<T>()

不建议在部署中使用Resources加载资源,尤其是WebGL和移动平台

在MINE中新增.bundle词条

web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".unity3d" mimeType="application/binary" />
            <mimeMap fileExtension=".bundle"		mimeType="application/binary" />
            <mimeMap fileExtension=".unityweb" mimeType="application/binary" />
        </staticContent>
        <directoryBrowse enabled="true" />
    </system.webServer>
</configuration>

web.config放在包体根目录下

4.中文字体缺失,下载后缀名为ttf的字体进行替换
选择需要替换字体的text组件的父结点,使用以下脚本可快速替换字体,也可以修改通配符,从而修改替换策略

using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class ChangeChineseFont : Editor
{
    static string fontPath = "Assets/Fonts/fontName.ttf";
    static string chinese = @"[\u4e00-\u9fa5]";
    [MenuItem("[Unity2016-2022-Neo]/Change Chinese Font")]
    static void Main()
    {
        var selection = Selection.activeTransform;
        if (selection != null)
        {
            var texts = selection.GetComponentsInChildren<Text>(true);
            for (int i = 0; i < texts.Length; i++)
            {
                if (Regex.IsMatch(texts[i].text, chinese))
                    texts[i].font = AssetDatabase.LoadAssetAtPath<Font>(fontPath);
            }
        }
    }
}

5.遗留问题
动态加载光照贴图会变暗,shader中有一个参数设置有问题,暂未找到是那个参数

你可能感兴趣的:(Unity,3D与编程语言,unity,3d,ios)