利用反射机制给View面板脚本里的组件字段赋值

当UI脚本上需要赋值的组件太多的时候,利用反射机制自动给参数赋值就显得很方便。只需要参数名称和UI节点的名称相一致(可以定义自己的匹配规则)
    /// 
    /// 给字段赋值
    /// 
    /// 
    /// 
    /// 
    public static void SetFieldValue(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);
    }

    /// 
    /// 递归函数给类里的字段赋值
    /// 
    /// 
    /// 
    /// 
    /// 
    private static void RecursiveSetValue(Transform root,List 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);
                }
            }
        }
    }

    /// 
    /// 判断字段的名称和节点的名称是否匹配
    /// 
    /// 
    /// 
    /// 
    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());
    }

你可能感兴趣的:(unity)