Unity 编辑器扩展之反射重载的私有方法

陌路散爱 提交于 2019-12-23 09:27:02

效果:

在这里插入图片描述

直接上菜了喂

using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

public class MyReflection : EditorWindow
{
    /*
     * 反射获取私有方法
     */
    [MenuItem("MyEditor/反射/MyReflectionTest/GetName()")]
    public static void Execute()
    {
        Type type = typeof(MyReflectionTest);
        object obj = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod("GetName", BindingFlags.NonPublic | BindingFlags.Instance,null, CallingConventions.Standard, new Type[] { },null);
        method.Invoke(obj,null);
    }

    [MenuItem("MyEditor/反射/MyReflectionTest/GetName(string name)")]
    public static void Execute1()
    {
        Type type = typeof(MyReflectionTest);
        object obj = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod("GetName", BindingFlags.NonPublic | BindingFlags.Instance,null, CallingConventions.Standard, new Type[] {typeof(string) }, null);
        object[] parameters = new object[] { "LF" };
        method.Invoke(obj, parameters);
    }

    [MenuItem("MyEditor/反射/MyReflectionTest/GetName(string name,int age)")]
    public static void Execute2()
    {

        Type type = typeof(MyReflectionTest);
        object obj = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod("GetName", BindingFlags.NonPublic | BindingFlags.Instance,null, CallingConventions.Standard, new Type[] {typeof(string) , typeof(int) }, null);
        object[] parameters = new object[] { "LF", 18 };
        method.Invoke(obj, parameters);
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyReflectionTest : MonoBehaviour
{
    private string _name = "PCJ";

    private void GetName()
    {
        Debug.Log("我的名字:" + _name);
    }

    private void GetName(string _name)
    {
        Debug.Log("我的名字:" + _name);
    }

    private void GetName(string _name, int _age)
    {
        Debug.Log("我的名字:" + _name + "  我的岁数:" + _age);
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!