I have searched far and wide, and I cannot find a solution to my problem, however it seems to be something that would have a solution.
Here’s the thing: I made a UI button object, not the regular one, a complicated one. The thing is, I want to have three of these, all managed by the same script. This script is meant to detect button presses, but it is not a simple OnClick() event thing, because if the player holds the mouse button but removes the cursor from the button, I do not want the click to count, thus I need to use something else than a regular Button component.
The point is, the action that needs to be performed is different for each of these buttons, so I cannot just hardcode which method to use. I need some sort of reference for these methods, accessible from the Unity inspector. I need something very similar to the method choice in EventTrigger, in which you literally choose the method to be executed.

But I need this to be a parameter to the script, which manages these buttons.
Thanks in advance.
1 Like
You could make an enum, and react to that enum with a switch.
There are also other solutions, some are harder to implement than others.
Tell me how knowledgeable you are with the C# in general.
Hi! I am not very knowledgeable, I started learning to use C# only in the context of Unity a couple of days ago. I believe, however, that there won’t be any trouble with learning new things quickly if necessary. I have a fair amount of experience with C++ though, and while I know these two languages have a lot of differences, they share some similarities too, so I am familiar with enumerators.
I’d prefer to stay away from a switch of sorts, or anything else that requires hardcoding the method references. It would be very appreciated if there was a way to pass a reference to a method as argument to a script.
I really hope I can get this resolved.
well in that case you could use reflection to get what you need.
you basically want to make an enum field, and then use this enum to make a string, with which you can obtain a particular MethodInfo which you can then Invoke.
here’s an example
public class MyReflectiveScript : MonoBehaviour {
[SerializeField] public SomeMethodsEnum method;
MethodInfo _methodInfo;
public enum SomeMethodsEnum {
Method1,
Method2,
Method3
}
void Awake() {
_methodInfo = this.GetType().GetMethod(method.ToString());
if(_methodInfo == null) Debug.LogWarning($"Method {methodName} does not exist.");
}
void Start() {
_methodInfo?.Invoke(this, null); // you could pass arguments instead of null
}
// make sure the methods are public, otherwise you have to set binding flags
public void Method1() {
Debug.Log("This is Method1 answering to call.");
}
public void Method2() {
Debug.Log("This is Method2 answering to call.");
}
// intentionally no Method3
}
I hope this is what you meant.