47 lines
1.4 KiB
C#
47 lines
1.4 KiB
C#
|
using System.Linq;
|
||
|
using Newtonsoft.Json;
|
||
|
using UnityEngine;
|
||
|
|
||
|
public static class SerializeUtils
|
||
|
{
|
||
|
|
||
|
public static string GetPath(this GameObject gameObject)
|
||
|
{
|
||
|
return string.Join("/", gameObject.GetComponentsInParent<Transform>().Select(t => t.name).Reverse().ToArray());
|
||
|
}
|
||
|
|
||
|
public static string ToSavable(this Vector3 vector3)
|
||
|
{
|
||
|
return JsonConvert.SerializeObject(new []{vector3.x, vector3.y, vector3.z});
|
||
|
}
|
||
|
|
||
|
public static string ToSavable(this MonoBehaviour mono)
|
||
|
{
|
||
|
return JsonConvert.SerializeObject(mono.gameObject.GetPath());
|
||
|
}
|
||
|
|
||
|
public static T FromSavable<T>(this string saveString)
|
||
|
{
|
||
|
if (typeof(T) == typeof(Vector3))
|
||
|
{
|
||
|
var vec3arr = JsonConvert.DeserializeObject<float[]>(saveString);
|
||
|
//虽然很丑陋,但暂时想不到更好的办法了
|
||
|
return (T)(object)(new Vector3(vec3arr[0], vec3arr[1], vec3arr[2]));
|
||
|
}
|
||
|
if (typeof(T).IsSubclassOf(typeof(MonoBehaviour)))
|
||
|
{
|
||
|
var gameObjectPath = JsonConvert.DeserializeObject<string>(saveString);
|
||
|
var go = GameObject.Find(gameObjectPath);
|
||
|
if (!go)
|
||
|
{
|
||
|
Debug.LogError($"没有找到物体: {gameObjectPath}");
|
||
|
return default;
|
||
|
}
|
||
|
return go.GetComponent<T>();
|
||
|
}
|
||
|
|
||
|
return default;
|
||
|
}
|
||
|
|
||
|
}
|