我在 Unity Webgl 上做一個專案,只有在我構建專案時才會出現錯誤(在編輯器中它作業正常)。基本上,我使用 Jsonblob 鏈接將引數分配給我制作的自定義結構。
錯誤說:Could not parse response {object}. Exception has been thrown by the target of an invocation.{object} 是我在 jsonblob 網站中使用的 json。
我正在使用的結構如下所示:
public struct GameSettings
{
public String venueName { get; set; }
public Monitor[] monitors { get; set; }
public Flag[] flags { get; set; }
public InformationMonitor[] informationMonitors { private get; set; }
public Banner[] banners { get; set; }
private const int MAX_MONITOR_LENGHT = 4;
}
雖然我獲取資料并分配資料的函式如下所示:
public GameSettings gameSettings;
public void Awake()
{
isRecovered = false;
GetData((response) => {
isRecovered = true;
gameSettings = response;
});
}
public async void GetData(System.Action<GameSettings> callback)
{
var url = jsonURL;
var httpClient = new HttpClient(new JsonSerializationOptions());
var result = await httpClient.Get<GameSettings>(url);
callback(result);
}
正如錯誤所說,它似乎無法決議物件,盡管我真的不明白為什么會這樣,尤其是當專案在編輯器中正常作業時為什么會發生這種情況,我錯過了什么嗎?
uj5u.com熱心網友回復:
由于 WebGL 不支持多執行緒async, WebGL 也HttpClient完全不支持(另見此處)。
您應該使用UnityWebrequest.Getand 進行 JSON 反序列化,要么使用內置的,JsonUtility要么Newtonsoft Json.NET作為包提供并預裝在最新版本中。
例如像
// In order to use the built-in serializer your types need to be [Serializable]
[Serializable]
public struct GameSettings
{
private const int MAX_MONITOR_LENGHT = 4;
// Note that all nested types also need to be [Serializable]
// Also at least the built-in JsonUtility only supports fields by default, no properties
// so either make them all fields or use Newtonsoft
// or enforce serialization using the undocumented [field: SerializeField] for each property
public string venueName;
public Monitor[] monitors;
public Flag[] flags;
public InformationMonitor[] informationMonitors;
public Banner[] banners;
}
public GameSettings gameSettings;
public string jsonURL;
// Start can be a Coroutine, if it returns IEnumerator it is automatically
// statred as a Coroutine by Unity
private IEnumerator Start()
{
isRecovered = false;
// you can simply yield another IEnumerator
yield return GetData();
}
private IEnumerator GetData()
{
using(var www = UnityWebRequest.Get(jsonURL))
{
// Request and wait for the result
yield return www.SendWebRequest();
if(www.result != UnityWebRequest.Result.Success)
{
Debug.LogError($"failed due to \"{www.error}\"", this);
yield break;
}
// now this depends on how good your types are (de)serializable
// either the built-in way
gameSettings = JsonUtiltiy.FromJson<GameSettings>(www.downloadHandler.text);
// or directly using Newtonsoft
gameSettings = JsonConvert.DeserializeObject<GameSettings>(www.downloadHandler.text);
isRecovered = true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452167.html
