Hey guys,
I want to check if a button is clicked.
I can do something like this
buttons[0].GetComponent<Button>().onClick.AddListener(TaskOnClick1);
but I want to use same button many times by changing its name and many task on click events. for example
if I click button at the second scene it will run TaskOnClick1 and if I click it at third scene TaskOnClick2 but it should be the same button.
is there a way to do it like
Void ChangeFunction(string FunctionName){
button[0].GetComponent<Button>().onClick.AddListener(FunctionName);
}
I Know that function is not a parameter but I should be able to give it as parameter. (Thats my biggest question
)
And another Question is that if I can detect a button click without OnClick.AddListener
for example if I Click 2nd button (ChoiceButton2) there will be a function which is declared by Unity and it gives me button name as a string.
There could be an easier way that i cannot think of. if there is I’m open to ideas.
Thanks for your helps
void ChangeFunction( UnityEngine.UnityEvents.UnityAction action ){
button[0].GetComponent().onClick.RemoveAllListeners();
button[0].GetComponent().onClick.AddListener(action);
}
But you have to provide a delegate to this function, and unfortunately, you won’t be able to do this using the editor, only through code:
void Start()
{
ChangeFunction( () => Debug.Log("Hello world") ) ;
}
You may be able to call a function by its name, but it’s less efficient.
(Following code not tested)
// Put `using System.Reflection;` at the top of your file
void ChangeFunction( string functionName ){
button[0].GetComponent<Button>().onClick.RemoveAllListeners();
button[0].GetComponent<Button>().onClick.AddListener( () =>
{
Type t = this.GetType();
MethodInfo method = t.GetMethod(functionName);
if( method != null )
method.Invoke(this, null);
});
}
Detecting the click on your UI button can be done in various ways:
- onClick.AddListener
- Attaching a script implementing
IPointerClickHandler
interface
- Ataching an EventTrigger component
In all these three cases, you will have to implement your own function to retrieve the button name. Without more information,it will be hard to help you.