2016-07-28 100 views
2

這個問題的實例是用於Unity3D的實用程序腳本,但問題是剛剛在C#;尋找方法

我提供的字符串(onClickCallbackPath)的腳本看起來像「GameObjectName.ComponentTypeName.CallbackDelegateName」。

查找遊戲對象和組件是沒有問題的,但看看這個代碼:

string[] ss = onClickCallbackPath.Split ("." [0]); 
    Transform onClickTarget = Tools.FindDeepChild (transform.root, ss [0]); 
    MonoBehaviour[] allComponentsOnTarget = onClickTarget.GetComponents<MonoBehaviour>(); 

    foreach (MonoBehaviour mb in allComponentsOnTarget) 
    { 
     if (mb.GetType().Name == ss [1]) 
     { 
      MethodInfo[] methods = mb.GetType().GetMethods (BindingFlags.Public); 

      foreach (MethodInfo mi in methods) 
      { 
       if (mi.Name == ss [2]) 
       { 
        // And here is how I imagine it to work, and look for something similar... 
        // but of course there is no GetInstance method in MethodInfo 
        Action a = (Action) mi.GetInstance(mb); 
        break; 
       } 
      } 

      break; 
     } 
    } 

正如你看到的,我需要找到Action類型的對象(我確定它是法正確的簽名),從我發現的MonoBehaviour內。

我想看看所有的MethodInfo屬性有類似的東西,我找了,也試圖找到網解決方案(這裏也對SO),但沒有成功。我敢打賭,找到解決方案的問題只是錯誤地指出了問題。

但我希望你明白什麼是我的問題。

任何幫助表示讚賞。

回答

5

什麼你要找的是

(Action)Delegate.CreateDelegate(typeof(Action), mb, mi) 
+0

完美!謝謝。 –