Unity WebGL可编辑配置文件

时间:2019-04-23 06:12:39

标签: unity3d unity-webgl

如何使Unity WebGL项目读取一种配置文件(任何格式),该文件可在Unity工作区中的“构建”之后进行编辑。

下面是Build目录的示例,其中包含打包的文件 enter image description here

用例是让此WebGL项目使用的后端API在托管服务器上可配置,以便播放器/用户浏览它时,它知道在何处连接到后端API。

我目前可以探讨的最接近的部分是实现自定义Javascript browser scripting。可以从Unity使用任何建议或任何现有的API吗?

1 个答案:

答案 0 :(得分:0)

针对该问题的所选解决方案的更新。使用了Javascript browser scripting方法。

总共要创建3个文件:

  1. WebConfigurationManager.cs
    • 将其放置在资产文件夹中。该文件是C#代码的主要条目,它决定从另一个C#类(使用统一编辑器)的默认值或使用浏览器脚本方法获取Web配置的位置。检索(通过浏览器浏览发行版时)
  2. WebConfigurationManager.jslib
    • 将其放置在与WebConfigurationManager.cs相同的文件夹中。此文件是javascript代码,将由浏览器加载。
  3. web-config.json
    • 您的JSON配置。 Web配置文件可以托管在任何地方,例如下面的示例,位于发行版本构建文件夹的根目录下,您必须知道文件的加载位置,例如https://<website>/web-config.json

// WebConfigurationManager.cs
using System;
using UnityEngine;
using System.Runtime.InteropServices;
using AOT;

public class ConfigurationManager : MonoBehaviour
{

#if UNITY_WEBGL && !UNITY_EDITOR
    // Load the web-config.json from the browser, and result will be passed via EnvironmentConfigurationCallback 
    public delegate void EnvironmentConfigurationCallback(System.IntPtr ptr);

    [DllImport("__Internal")]
    private static extern void GetEnvironmentConfiguration(EnvironmentConfigurationCallback callback);

    void Start()
    {
        GetEnvironmentConfiguration(Callback);
    }

    [MonoPInvokeCallback(typeof(EnvironmentConfigurationCallback))]
    public static void Callback(System.IntPtr ptr)
    {
        string value = Marshal.PtrToStringAuto(ptr);
        try
        {
            var webConfig = JsonUtility.FromJson<MainConfig>(value);
            // webConfig contains the value loaded from web-config.json. MainConfig is the data model class of your configuration.
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to read configuration. {e.Message}");
        }
    }
#else
    void Start()
    {
        GetEnvironmentConfiguration();
    }

    private void GetEnvironmentConfiguration()
    {
        // do nothing on unity editor other than triggering the initialized event

        // mock the configuration for the use of Unity editor
        var testConfig = JsonUtility.FromJson<MainConfig>("{\n" +
              "  \"apiEndpoint\": \"ws://1.1.1.1:30080/events\",\n" +
              "  \"updateInterval\": 5\n" +
              "}");
        Debug.Log(testConfig.apiEndpoint);
        Debug.Log(testConfig.updateInterval);
    }

#endif
}
// WebConfigurationManager.jslib
mergeInto(LibraryManager.library, {

  GetEnvironmentConfiguration: function (obj) {
    function getPtrFromString(str) {
      var buffer = _malloc(lengthBytesUTF8(str) + 1);
      writeStringToMemory(str, buffer);
      return buffer;
    }

    var request = new XMLHttpRequest();
    // load the web-config.json via web request
    request.open("GET", "./web-config.json", true);
    request.onreadystatechange = function () {
      if (request.readyState === 4 && request.status === 200) {
        var buffer = getPtrFromString(request.responseText);
        Runtime.dynCall('vi', obj, [buffer]);
      }
    };
    request.send();
  }

});
相关问题