Редактируемый файл конфигурации Unity WebGL

Как заставить проект Unity WebGL читать своего рода файл конфигурации (любого формата), который можно редактировать после «сборки» из рабочей области Unity.

Ниже приведен образец каталога сборки, который содержит упакованные файлы  введите описание изображения здесь

Вариант использования заключается в том, чтобы внутренний API, используемый этим проектом WebGL, был настраиваемым на сервере хостинга, чтобы при его просмотре игрок / пользователь знал, где подключиться к внутреннему API.

Ближайшая часть, которую я мог изучить в настоящее время, - это реализация пользовательского сценариев браузера Javascript. Любой совет или любой существующий API можно использовать из Unity?


person ChinKang    schedule 23.04.2019    source источник


Ответы (1)


Обновление выбранного решения для этого вопроса. Использовался метод JavaScript-скрипт браузера.

Всего необходимо создать 3 файла:

  1. WebConfigurationManager.cs
    • Place it in the asset folder. This file is the main entry for the C# code, it decides where to get the web configuration, either via the default value from another C# class (while using the unity editor), or using the browser scripting method to retrieve (while browsing the distribution build via browser).
  2. WebConfigurationManager.jslib
    • Place it the same folder as WebConfigurationManager.cs. This file is the javascript code, to be loaded by browser.
  3. web-config.json
    • Your JSON configuration. The web configuration file could be hosted anywhere, example below placed under the root of the distribution build folder, you'll have to know where to load the file, for example 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();
  }

});
person ChinKang    schedule 19.08.2019