Hey!
This is maybe a simple question but i want to know how, when creating a new Button UI prefab, to create an event which will run a specific function in the player script that need the text in the text component of the child of the button. That it, sorry for bad english. Remember: if you don’t understand tell me.
You can use lambda expressions:
public class Test : MonoBehaviour
{
public Button button; // prefab goes here
public void Start() {
Button newButton = Instantiate(button);
Text text = button.GetComponentInChildren<Text>();//Or any other way to find Text component
newButton.onClick.AddListener(()=>{Text txt = text; SomeMethod(txt);});
}
public void SomeMethod(Text text) {
Debug.Log("Button clicked! Its text is "+text.text);
}
}
Note: part ()=>{Text txt = text; SomeMethod(text);} is the magic here, it’s declaration of anonymous method (a.k.a. lambda expression) which means:
() - no arguments
=> should do
{…} operations to do. Last statement is returned as return value (in this case, void).
Note: because of how Unity compiler works, without “Text txt = text;” part incorrect behaviour is possible.