How to write a script for an existing button
I'm absolutely positive this has already been asked, but I'm fairly new to scripting and Unity in general so I'm having a lot of trouble parsing through the information in a way I can use it.
I have created a button in the editor and placed it where I want it to go. I've also written a class with methods to perform a function, But I just can't figure out how to attach the functions I want to the button clicks.
I've created a new script for my button, but I'm not sure how to format the code for the button's use, and I'm not sure what to call in the script to attach the button's click to the function.
I've seen people post using "MyButton" and others creating a new object "Button foo = new Button()" but how do I make the script recognize the button I'm trying to attach it to?
Thanks for your help!
Edit: Through further digging, I've found reference to "GetComponent." Can anyone help to explain this to me?
Answer by cjdev · Aug 29, 2015 at 02:16 AM
There are a few ways you can reference a GameObject in your scene. One of the ways is to find it by name with GameObject.Find(). After you have the GameObject you have to get the Component you want to work with from that object, although with UI it is common for objects to have children elements that are actually the objects you are after. To get around this there is the GetComponentInChildren function that lets you get a component in a child object. Here's an example of how it might work:
void Start()
{
//Gets the GameObject named "Canvas" that the Canvas component is attached to
GameObject canvasObject = GameObject.Find("Canvas");
//Gets the Button component from the child GameObject named "Button"
Button yourButton = canvasObject.GetComponentInChildren<Button>();
//Adds your event listener to the button to call your function on click
yourButton.onClick.AddListener(() => OnClickFunction());
//Sets the text property in the Text component of the Button
yourButton.GetComponentInChildren<Text>().text = "Foo";
}
private void OnClickFunction()
{
Debug.Log("Foo");
}