Unity根据字符串拿到类名并调用方法和属性(反射机制)

例如:我有一个变量string 我想通过这个sting 去拿到对应的类,可以调用这个类的方法拿到这个类的属性,可以这样写

public class ReflectionTest : MonoBehaviour
{

void Start()
    {
        GetClass("CeshiFanse");
    }

    
    private void GetClass(string className)
    {
        //通过string类型的strClass获得同名类“type”
        Type type = Type.GetType(className);
        //创建type类的实例 "obj"
        object obj = System.Activator.CreateInstance(type);
        //拿到这个类的 同名String strw
        FieldInfo fieldInfo = type.GetField("strw");
        Debug.Log(fieldInfo.GetValue(obj));
        //拿到这个类的同名 方法
        MethodInfo method = type.GetMethod("Ceshi");
        //调用方法
        method.Invoke(obj, null);
        
    }

}

public class CeshiFanse : MonoBehaviour

{
    public string tran="你好嘛";
    public string strw = "ssuiso";
    private void Start()
    {
        strw = "6666";
    }
    public void Ceshi() 
    {
        Debug.Log("你好");
    }
    
}

注意:如果脚本继承了MonoBehaviour类,这个脚本一定要挂在面板上,没有继承就不用,否则会报空

猜你喜欢

转载自blog.csdn.net/weixin_39543044/article/details/121418915