Reputation: 43
I have a MainButton object with a Button component. A component has a property (or what it is) On Click (). This property can have an object and a method that will be executed by pressing a button. I tried to set these values in the inspector, but these values are not saved in the prefab, because they are assigned from Assets, and not from Scene. How to assign this method and object through programming? Who didn't understood - I need to change properties (object, method) of the event "OnClick()" by the script.
Upvotes: 0
Views: 209
Reputation: 1074
You're looking for the Unity.OnClick UnityEvent
.
public class Example : MonoBehaviour
{
//Make sure to attach these Buttons in the Inspector
public Button m_YourFirstButton, m_YourSecondButton, m_YourThirdButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
m_YourSecondButton.onClick.AddListener(delegate {TaskWithParameters("Hello"); });
m_YourThirdButton.onClick.AddListener(() => ButtonClicked(42));
m_YourThirdButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
void TaskWithParameters(string message)
{
//Output this to console when the Button2 is clicked
Debug.Log(message);
}
void ButtonClicked(int buttonNo)
{
//Output this to console when the Button3 is clicked
Debug.Log("Button clicked = " + buttonNo);
}
}
Upvotes: 1