I am trying to do a simple thing:
- Create a new
GameObject - Add a
Buttoncomponent to theGameObject. - Add a persistent Listener to
Button'sOnClickevent.
The method I am trying to register is in some other script. Here is piece of code that I am trying:
MyScript myScriptInstance = FindObjectOfType<MyScript>();
var go = new GameObject();
var btn = go.AddComponent<Button>();
var targetinfo = UnityEvent.GetValidMethodInfo(myScriptInstance,
"OnButtonClick", new Type[]{typeof(GameObject)});
var action = (UnityAction) Delegate.CreateDelegate(typeof(UnityAction),go, targetinfo, false);
UnityEventTools.AddPersistentListener(btn.onClick, action);
MyScript.cs looks like this:
public class MyScript : MonoBehaviour
{
public void OnButtonClick(GameObject sender)
{
// do some stuff here.
}
}
When I run this code, Buttons Onclick listener is empty like this:

If I change the line
var action = (UnityAction) Delegate.CreateDelegate(typeof(UnityAction),
go, targetinfo, false);
to
var action = (UnityAction) Delegate.CreateDelegate(typeof(UnityAction),
go, targetinfo, true);
I get :
ArgumentException: method argument length mismatch System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, Boolean throwOnBindFailure)
I followed these instructions but don't know what went wrong here.
Any kind of help is truly appreciated.

EventSystems.IPointerClickHandler?