C # using reflection achieved according to a string, a class to find variable names and the same variable character string, and assign it a value, this function may be used when responding to read table, and the like:
1, the inside of the character string type variables found
Find FieldTest class, the variable named name
FieldTest fieldTest = new FieldTest();
System.Reflection.FieldInfo fieldInfo = fieldTest.GetType().GetField("name");
To name variable assignment:
fieldInfo.SetValue(fieldTest, "亚里士多德");
2, the following is the complete code:
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
FieldTest fieldTest = new FieldTest();
System.Reflection.FieldInfo fieldInfo = fieldTest.GetType().GetField("name");
fieldInfo.SetValue(fieldTest, "亚里士多德");
fieldInfo = fieldTest.GetType().GetField("age");
fieldInfo.SetValue(fieldTest, 123);
print(string.Format("{0}的年龄有{1}岁了。", fieldTest.name, fieldTest.age));
}
}
public class FieldTest
{
public string name;
public int age;
}