Unity-DebugX/Runtime/Internal/StaticDataLoader.cs

58 lines
1.8 KiB
C#
Raw Normal View History

2025-02-22 17:25:54 +08:00
using System.Linq;
using System.Reflection;
using UnityEngine;
2025-02-24 10:47:07 +08:00
namespace DCFApixels.DebugXCore
2025-02-22 17:25:54 +08:00
{
2025-02-24 10:47:07 +08:00
public static class StaticDataLoader
2025-02-22 17:25:54 +08:00
{
public static T Load<T>(T instance, string path)
{
object obj = instance;
var type = obj.GetType();
2025-02-24 10:47:07 +08:00
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
2025-02-22 17:25:54 +08:00
var prefab = Resources.Load<GameObject>(path);
if (prefab == null)
{
Debug.LogError($"{path} not found");
return (T)obj;
}
if (fields.Count() <= 0)
{
Debug.LogError($"{typeof(T).Name} no fields");
return (T)obj;
}
2025-02-24 10:47:07 +08:00
foreach (var field in fields.Where(o => o.FieldType == typeof(Mesh)))
2025-02-22 17:25:54 +08:00
{
var child = prefab.transform.Find(field.Name);
var meshFilter = child.GetComponent<MeshFilter>();
if (meshFilter != null)
{
field.SetValue(obj, meshFilter.sharedMesh);
}
else
{
Debug.LogWarning(field.Name + " not found");
}
}
2025-02-24 10:47:07 +08:00
foreach (var field in fields.Where(o => o.FieldType == typeof(Material)))
{
var child = prefab.transform.Find(field.Name);
var meshFilter = child.GetComponent<Renderer>();
if (meshFilter != null)
{
field.SetValue(obj, meshFilter.sharedMaterial);
}
else
{
Debug.LogWarning(field.Name + " not found");
}
}
2025-02-22 17:25:54 +08:00
return (T)obj;
}
}
}