共计 1406 个字符,预计需要花费 4 分钟才能阅读完成。
当 UI 脚本上须要赋值的组件太多的时候,利用反射机制主动给参数赋值就显得很不便。只须要参数名称和 UI 节点的名称相一致 (能够定义本人的匹配规定)
/// <summary>
/// 给字段赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="root"></param>
/// <param name="tObj"></param>
public static void SetFieldValue<T>(this Transform root,T tObj)
{var fields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic)?.Where(p => p.FieldType.IsSubclassOf(typeof(Component))).ToList();
RecursiveSetValue(root, fields, tObj);
}
/// <summary>
/// 递归函数给类里的字段赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="root"></param>
/// <param name="fieldInfos"></param>
/// <param name="tObj"></param>
private static void RecursiveSetValue<T>(Transform root,List<FieldInfo> fieldInfos,T tObj)
{if (fieldInfos == null || fieldInfos.Count == 0) return;
for (int i = 0; i < root.childCount; i++)
{var child = root.GetChild(i);
RecursiveSetValue(child, fieldInfos,tObj);
for (int j = fieldInfos.Count - 1; j >= 0; j--)
{var fieldInfo = fieldInfos[j];
if (fieldInfo.FieldType.IsSubclassOf(typeof(Component)) && fieldInfo.Name.IsMatch(child.name))
{var component = child.GetComponent(fieldInfo.FieldType);
fieldInfo.SetValue(tObj, component);
fieldInfos.RemoveAt(j);
}
}
}
}
/// <summary>
/// 判断字段的名称和节点的名称是否匹配
/// </summary>
/// <param name="name"></param>
/// <param name="transName"></param>
/// <returns></returns>
private static bool IsMatch(this string name,string transName)
{var temp = name.StartsWith("_") ? name.Substring(1, name.Length - 1) : name;
return temp.ToLower().Equals(transName.ToLower());
}
正文完