C#反射不调用方法

时间:2016-05-18 22:22:52

标签: c# reflection invoke

我正在使用带反射的Unity,我试图调用某个方法名称Start,但我的代码没有调用它

这是ModLoader.cs:

using UnityEngine;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Collections.Generic;

public class ModLoader : MonoBehaviour {
    List<MethodInfo> modMethods = new List<MethodInfo>();

    // Use this for initialization
    void Start () {
        if (!Directory.Exists (Application.dataPath + "/../Mods")) {
            Directory.CreateDirectory (Application.dataPath + "/../Mods");
        }

        foreach (var mod in Directory.GetFiles(Application.dataPath + "/../Mods", "*.dll")) {
            var assembly = Assembly.LoadFile(mod);
            foreach (var type in assembly.GetTypes()) {
                foreach (var method in type.GetMethods()) {
                    modMethods.Add (method);
                }
            }
        }

        //Execute Start method in all mods
        foreach (MethodInfo method in modMethods) {
            print (method.Name);
            if (method.Name == "Start" && method.GetParameters().Length == 0 && method.IsStatic) {
                method.Invoke (null, new object[]{  });
            }
        }
    }

    // Update is called once per frame
    void Update () {
        //Execute Update method in all mods
        foreach (MethodInfo method in modMethods) {
            if (method.Name == "Update" && method.GetParameters().Length == 0 && method.IsStatic) {
                method.Invoke (null, new object[]{  });
            }
        }
    }
}

这是我的mod(.dll):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class Class1 {
    static void Start () {
        Debug.Log("hello world");

        foreach (GameObject go in GameObject.FindObjectsOfType<GameObject>()) {
            if (go.GetComponent<MeshRenderer>()) {
                go.GetComponent<MeshRenderer>().material.color = new Color(1f, 0f, 0f);
            }
        }
    }
}

我有来自&#34; Mods&#34;文件夹,我知道我的脚本找到它,我只是不知道为什么方法ID没有被调用。

2 个答案:

答案 0 :(得分:2)

模块中的Start方法是私有的。默认情况下,反射适用于公共方法。你需要公开它:

public class Class1 {
    public static void Start () {
        Debug.Log("hello world");

        foreach (GameObject go in GameObject.FindObjectsOfType<GameObject>()) {
            if (go.GetComponent<MeshRenderer>()) {
                go.GetComponent<MeshRenderer>().material.color = new Color(1f, 0f, 0f);
            }
        }
    }
}

或为GetMethods方法指定BindingFlags。你需要BindingFlags.Static和BindingFlags.NonPublic

type.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)

答案 1 :(得分:0)

如果public方法中没有Start关键字,则不会公开,GetMethods()默认只查找公共方法。

公开Start,或将type.GetMethods()更改为type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)