こんにちはー!!
Json からUnity2dのステージのデータを取ろうとしています。
その時、コンポーネントの値を変えたいと思い、この方法をやりました。
Reflectionを使ったりして、結構複雑でした。
ReflectionTest コンポーネントの内容は次のようにします。
これを、GameObject1 にアタッチすればできます。
安全性は・・
しかし、コンポーネント内すべてのフィールドにアクセスできるのは
ちょっとセキュリティが・・・なので、
特定の属性(ここではPermitReflection)がついたフィールドのみにアクセスできるようにします。
Reflectionに使ったしたコード(2つ上のコード)を、次のように編集します。
Type componentType = Type.GetType(componentType); Attribute fieldAttribute = Attribute.GetCustomAttribute(componentType.GetField(fieldName), typeof(PermitReflectionAttribute)); if (fieldAttribute != null) // 属性が存在する場合のみ { Component targetComponent = GameObject.Find(gameObjectName).GetComponent(componentName); Type fieldType = componentType.InvokeMember(fieldName, BindingFlags.GetField, null, targetComponent, null).GetType(); object parameter; // 汎用性を重視して、型がどんな場合でもstringからParseできるように if (fieldType == typeof(string)) { parameter = fieldVal; } else if (fieldType == typeof(int)) { parameter = int.Parse(fieldVal); } componentType.InvokeMember(fieldName, BindingFlags.SetField, null, targetComponent, new object[] { parameter }); } } // 属性を追加 [AttributeUsage(AttributeTargets.Field)] public class PermitReflectionAttribute : Attribute { }
ReflectionTest コンポーネントは次のように変更します。
PermitReflectionAttributeですが、属性として指定する場合は、
Attributeを抜いて、PermitReflectionとします。