I am trying to do a simple thing:
- Create new
GameObject - Add a component
Buttonto the gameObject. - Add a persistent listener to the onClick event.
The method I'm trying to register is in another script. Here is the code snippet I'm trying to do:
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)
{
}
}
When I run this code, the Onclick buttons to listen for empty ones:

If I changed 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: mismatch of the argument length of the System.Delegate.CreateDelegate method (Type System.Type, System.Object method firstArgument, System.Reflection.MethodInfo, Boolean throwOnBindFailure)
I followed these instructions , but I donβt know what is wrong here.
Any help is really appreciated.