Files
3d-bianpo/Assets/Scripts/Core/WebService.cs
2026-03-03 11:30:53 +08:00

310 lines
9.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Collections.Generic;
public class WebService : MonoBehaviour
{
private static WebService _instance;
public static WebService Instance
{
get
{
if (_instance == null)
{
string name = "WebService";
GameObject obj = GameObject.Find(name);
if (obj == null)
{
obj = new GameObject(name);
_instance = obj.AddComponent<WebService>();
}
else
{
_instance = obj.GetComponent<WebService>();
if (_instance == null)
{
_instance = obj.AddComponent<WebService>();
}
}
}
return _instance;
}
}
//网络图片资源缓存
private Dictionary<int, Texture2D> textureCache = new Dictionary<int, Texture2D>();
//图片下载
private Queue<LoadTextureTask> textureQueue = new Queue<LoadTextureTask>();
//图片加载完成
private bool isTextureQueueFinish = true;
void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
//获取本地数据
public void GetLocalData<T>(Action<T> callback, string code = null) where T : class
{
StartCoroutine(GetLocalDataCor(callback, code));
}
IEnumerator GetLocalDataCor<T>(Action<T> callback, string code) where T : class
{
string name = "JsonData/" + typeof(T).Name;
if (code != null)
{
name += "_" + code;
}
TextAsset textAsset = Resources.Load<TextAsset>(name);
yield return new WaitForEndOfFrame();
T t = null;
if (textAsset != null)
{
try
{
t = JsonUtility.FromJson<T>(textAsset.text);
}
catch (Exception e)
{
Debug.LogError("Json反序列化异常 type = " + typeof(T) + ", Exception : " + e.ToString());
}
}
else
{
Debug.LogErrorFormat("{0}.json is not found.", typeof(T).Name);
}
if (callback != null)
{
callback.Invoke(t);
}
}
public void GetText(string url, Action<string> callback)
{
StartCoroutine(GetTextCor(url, callback));
}
IEnumerator GetTextCor(string url, Action<string> callback)
{
UnityWebRequest unityWeb = UnityWebRequest.Get(url);
unityWeb.downloadHandler = new DownloadHandlerBuffer();
unityWeb.SetRequestHeader("Authorization", "tenantCode=CZFHSK&accessToken=52060d8c71d0e4a2d97c1b900acc8b1fa3a6928d");
yield return unityWeb.SendWebRequest();
if (unityWeb.result != UnityWebRequest.Result.ConnectionError && unityWeb.result != UnityWebRequest.Result.ProtocolError)
{
callback?.Invoke(unityWeb.downloadHandler.text);
}
else
{
Debug.LogError("Web请求失败, Error : " + unityWeb.error);
}
unityWeb.Dispose();
}
//Get通信
public void Get<T>(string url, Action<T> callback) where T : class
{
StartCoroutine(GetCor(url, callback));
}
IEnumerator GetCor<T>(string url, Action<T> callback) where T : class
{
UnityWebRequest unityWeb = UnityWebRequest.Get(url);
unityWeb.downloadHandler = new DownloadHandlerBuffer();
unityWeb.SetRequestHeader("Authorization", "tenantCode=CZFHSK&accessToken=52060d8c71d0e4a2d97c1b900acc8b1fa3a6928d");
yield return unityWeb.SendWebRequest();
T t = null;
if (unityWeb.result != UnityWebRequest.Result.ConnectionError && unityWeb.result != UnityWebRequest.Result.ProtocolError)
{
try
{
t = JsonUtility.FromJson<T>(unityWeb.downloadHandler.text);
}
catch (Exception e)
{
Debug.LogError("Json反序列化异常 type = " + typeof(T) + ", Exception : " + e.ToString());
}
}
else
{
Debug.LogError("Web请求失败 type = " + typeof(T) + ", Error : " + unityWeb.error);
}
if (callback != null)
{
callback.Invoke(t);
}
unityWeb.Dispose();
}
//Post通信
public void Post<T>(string url, object obj, Action<T> callback) where T : class
{
StartCoroutine(PostCor(url, obj, callback));
}
IEnumerator PostCor<T>(string url, object obj, Action<T> callback) where T : class
{
UnityWebRequest unityWeb = new UnityWebRequest(url, "POST");
if (obj != null)
{
string json = JsonUtility.ToJson(obj);
byte[] data = System.Text.Encoding.UTF8.GetBytes(json);
unityWeb.uploadHandler = new UploadHandlerRaw(data);
}
unityWeb.downloadHandler = new DownloadHandlerBuffer();
unityWeb.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
yield return unityWeb.SendWebRequest();
T t = null;
if (unityWeb.result != UnityWebRequest.Result.ConnectionError && unityWeb.result != UnityWebRequest.Result.ProtocolError)
{
try
{
t = JsonUtility.FromJson<T>(unityWeb.downloadHandler.text);
}
catch (Exception e)
{
Debug.LogError("Json反序列化异常 type = " + typeof(T) + ", Exception : " + e.ToString());
}
}
else
{
Debug.LogError("Web请求失败 type = " + typeof(T) + ", Error : " + unityWeb.error);
}
if (callback != null)
{
callback.Invoke(t);
}
unityWeb.Dispose();
}
//加载图片资源
public void GetTexture(string url, RawImage image, bool isCache = true)
{
if (url.Length == 0)
{
return;
}
int code = url.GetHashCode();
//缓存数据
if (textureCache.ContainsKey(code))
{
image.gameObject.SetActive(true);
image.texture = textureCache[code];
return;
}
//加入队列
LoadTextureTask task = new LoadTextureTask(url, image, isCache);
textureQueue.Enqueue(task);
//下载图片
if (isTextureQueueFinish)
{
StartCoroutine(GetTextureCor());
}
}
IEnumerator GetTextureCor()
{
isTextureQueueFinish = false;
LoadTextureTask task = textureQueue.Dequeue();
UnityWebRequest unityWeb = UnityWebRequestTexture.GetTexture(task.url);
yield return unityWeb.SendWebRequest();
if (unityWeb.result != UnityWebRequest.Result.ConnectionError && unityWeb.result != UnityWebRequest.Result.ProtocolError)
{
Texture2D texture = ((DownloadHandlerTexture)unityWeb.downloadHandler).texture;
//Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
task.image.gameObject.SetActive(true);
task.image.texture = texture;
//缓存
if (task.cache)
{
if (textureCache.ContainsKey(task.url.GetHashCode()))
{
textureCache[task.url.GetHashCode()] = texture;
}
else
{
textureCache.Add(task.url.GetHashCode(), texture);
}
}
}
else
{
Debug.LogError("图片加载失败失败, url : " + task.url + " error : " + unityWeb.error);
}
unityWeb.Dispose();
//递归
if (textureQueue.Count > 0)
{
StartCoroutine(GetTextureCor());
}
else
{
isTextureQueueFinish = true;
}
}
//获取AssetBundle
public void GetAssetBundle(string url, Action<AssetBundle> callback)
{
StartCoroutine(GetAssetBundleCor(url, callback));
}
IEnumerator GetAssetBundleCor(string url, Action<AssetBundle> callback)
{
UnityWebRequest unityWeb = UnityWebRequestAssetBundle.GetAssetBundle(url);
yield return unityWeb.SendWebRequest();
AssetBundle bundle = null;
if (unityWeb.result != UnityWebRequest.Result.ConnectionError && unityWeb.result != UnityWebRequest.Result.ProtocolError)
{
bundle = DownloadHandlerAssetBundle.GetContent(unityWeb);
}
else
{
Debug.LogError("Web请求失败 type = AssetBundle, Error : " + unityWeb.error);
}
if (callback != null)
{
callback.Invoke(bundle);
}
unityWeb.Dispose();
}
//判断是否在WebGL平台运行
public static bool IsRunningInWebGL()
{
return Application.platform == RuntimePlatform.WebGLPlayer;
}
}
//图片加载任务
public class LoadTextureTask
{
public string url;
public RawImage image;
public bool cache;
public LoadTextureTask(string _url, RawImage _image, bool _cache)
{
url = _url;
image = _image;
cache = _cache;
}
}