我有一个带有按钮组件的mainbutton对象。组件在click()上具有属性(或它的内容)。此属性可以具有一个对象和方法,该方法将通过按下按钮执行。我试图将这些值设置在检查员中,但是这些值并未保存在预制器中,因为它们是从资产分配的,而不是从场景中分配的。如何通过编程分配此方法和对象?谁没有理解 - 我需要通过脚本更改事件" onclick()"的属性(对象,方法)。
您正在寻找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);
}
}