How to create a onClick addlistener from text parameter?

I am instantiating button prefab to create various button dynamically. When I create the button I can use values from a class passed into the method that creates the button to change its appearance etc but for the life of me I cannot assign its onClick method to call.

So in the class passed in I have this:

	[System.Serializable]
	public class Action {

		public Sprite normalSprite;

		public Sprite pressedSprite;

		public GameObject methodParent;

		public string methodToCall;
	}

And in the method that receives this I have tried:

			newButton.GetComponent<TouchControlsKit.TCKButton> ().clickEvent.AddListener(obj.options *.methodToCall);*

Which fails because it wants an action not a string!
How do I tell addlistener that the string is the name of the method I want assigned to the onClick?
Thanks

Another solution there is to use the send message funtion that unity add, and that take the method name in parameter. Therefore, it’s easier. The problem is that this function will be called on every monobehaviour of this gameobject. The syntax is gameobject.SendMessage(“messageName”).

I think this can do for you :slight_smile:

Top of my head, I can think of two ways to solve this problem.

  1. Using reflection. This would be the closest to what you want to do. There is a simple and easy way to understand example [here][1]. Get the type of the object you want to call the method to, then using GetMethod, you can get the method by name, and call Invoke to call it.

I’m guessing it’ll end up looking something like this (I haven’t tested this, but it should work)

            newButton.GetComponent<TouchControlsKit.TCKButton>().clickEvent.AddListener(()=> 
            {
                Type thisType = obj.GetType();
                MethodInfo theMethod = thisType.GetMethod(obj.options*.methodToCall);*

theMethod.Invoke(obj);
});
2) If your methods are not going to change much, why use strings? List up an enum with the possible methods you can call, then make a Dictionary<enum, System.Action> where you store each method you want to call with its corresponding enum value. Less leeway for errors this way, since you can’t type any arbitrary string.
For example:
public enum Method
{
Method1,
Method2,
Method3,
}

[System.Serializable]
public class Action
{
public Sprite normalSprite;
public Sprite pressedSprite;
public GameObject methodParent;
public Method methodToCall;
}

Dictionary<Method, System.Action> methodList;
and then
System.Action method = methodList[obj.options*.methodToCall];*
newButton.GetComponent<TouchControlsKit.TCKButton>().clickEvent.AddListener(method);
of course, don’t forget to initialize your dictionary with the correct values.
_*[1]: .net - Calling a function from a string in C# - Stack Overflow