JsonLoaderManager.cs
1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class JsonLoaderManager : Singleton<JsonLoaderManager>
{
public static IEnumerator LoadJson(string remoteUrl,string localUrl,System.Action<string> onJsonReady)
{
string json = null;
bool loadedFromWeb = false;
using (UnityWebRequest uwr = UnityWebRequest.Get(remoteUrl))
{
uwr.timeout = 5; // 设置超时时间
yield return uwr.SendWebRequest();
if (uwr.result == UnityWebRequest.Result.Success)
{
json = uwr.downloadHandler.text;
loadedFromWeb = true;
Debug.Log("✅ 从网络加载成功");
}
else
{
Debug.LogWarning("⚠️ 网络加载失败,尝试加载本地 JSON:" + uwr.error);
}
}
if (!loadedFromWeb)
{
TextAsset localJson = Resources.Load<TextAsset>(localUrl);
if (localJson != null)
{
json = localJson.text;
Debug.Log("📁 从本地加载 JSON 成功");
}
else
{
Debug.LogError("❌ 本地 JSON 不存在!");
}
}
onJsonReady?.Invoke(json);
}
}