如何为事件分配按钮值

时间:2019-02-15 16:22:17

标签: c# unity3d

我有一个带有Button组件的MainButton对象。组件在单击()时具有属性(或它是什么)。此属性可以包含一个对象和一个将通过按按钮执行的方法。我试图在检查器中设置这些值,但这些值未保存在预制件中,因为它们是从资产而不是从场景分配的。如何通过编程分配该方法和对象?谁不理解-我需要通过脚本更改事件“ OnClick()”的属性(对象,方法)。

1 个答案:

答案 0 :(得分:1)

您正在寻找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);
    }
}