using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
public static class ReflectionHelper
{
private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
// --- 设置值 (支持 object) ---
public static void SetDeepValue(object target, string path, object newValue)
{
if (target == null || string.IsNullOrEmpty(path)) return;
string[] parts = path.Split('.');
SetDeepValueRecursive(target, parts, 0, newValue);
}
private static void SetDeepValueRecursive(object currentObj, string[] pathParts, int index, object newValue)
{
string memberName = pathParts[index];
Type type = currentObj.GetType();
FieldInfo field = type.GetField(memberName, Flags);
PropertyInfo prop = type.GetProperty(memberName, Flags);
if (field == null && prop == null)
{
// Debug.LogWarning($"找不到成员: {memberName}"); // 可选:调试用
return;
}
bool isLast = index == pathParts.Length - 1;
if (isLast)
{
// 到达终点:直接设置值
// 注意:这里可能需要处理类型转换,取决于你的 newValue 类型是否严格匹配
try
{
if (field != null) field.SetValue(currentObj, newValue);
else if (prop != null && prop.CanWrite) prop.SetValue(currentObj, newValue);
}
catch (Exception e) { Debug.LogError($"设置值失败 {memberName}: {e.Message}"); }
}
else
{
// 中间节点
object nextObj = field != null ? field.GetValue(currentObj) : prop.GetValue(currentObj);
if (nextObj == null) return;
SetDeepValueRecursive(nextObj, pathParts, index + 1, newValue);
// Struct 回写逻辑 (关键)
if (nextObj.GetType().IsValueType)
{
if (field != null) field.SetValue(currentObj, nextObj);
else if (prop != null && prop.CanWrite) prop.SetValue(currentObj, nextObj);
}
}
}
// --- 获取值 (支持 object) ---
public static object GetDeepValue(object target, string path)
{
object current = target;
foreach (string part in path.Split('.'))
{
if (current == null) return null;
Type type = current.GetType();
FieldInfo field = type.GetField(part, Flags);
if (field != null)
{
current = field.GetValue(current);
continue;
}
PropertyInfo prop = type.GetProperty(part, Flags);
if (prop != null)
{
current = prop.GetValue(current);
continue;
}
return null; // 路径中断
}
return current;
}
///
/// 遍历对象的所有字段和属性(递归地),查找值与目标值匹配的参数路径。
///
/// 要搜索的对象实例。
/// 要匹配的目标值。
/// 递归搜索的最大深度,防止无限循环。
/// 返回匹配参数的完整路径列表 (例如: "position.x")。
public static List FindParametersByValue(object target, object targetValue, int maxDepth = 10)
{
if (target == null || targetValue == null) return new List();
// 用于存储找到的路径
var results = new List();
// 用于防止循环引用(比如类 A 内部引用了类 B,类 B 内部又引用了类 A)
var visited = new HashSet