为什么我的Button不能与Unity类中的方法一起使用?

时间:2020-07-17 15:08:02

标签: c# unity3d

我有一个位于从另一个类继承的类中的按钮(此处应无关紧要) 并且以下代码与类中的按钮完美配合使用:

public class AttackState : State
{

    public AttackState(BattleSystem battleSystem) : base(battleSystem)
    {
        
    }
    
    public override void OnStateEnter()
    {
        Button btn = battleSystem.attackButton.GetComponent<Button>();
        Debug.Log("AttackState");
        btn.onClick.AddListener(() => Debug.Log("heya"));
        Debug.Log(btn.gameObject.name);    
    }

    public void Attack() {
        Debug.Log("Attacking");            
    }
}

将其更改为以下内容后:

public class AttackState : State
{

    public AttackState(BattleSystem battleSystem) : base(battleSystem)
    {
        
    }

    public override void OnStateEnter()
    {
        Button btn = battleSystem.attackButton.GetComponent<Button>();
        Debug.Log("AttackState");
        btn.onClick.AddListener(() => Attack());
        Debug.Log(btn.gameObject.name);

    }

    public void Attack() {
        Debug.Log("Attacking");        
    }

它不再起作用了。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

如何将方法添加到侦听器:

//Add a listener to the new Event. Calls MyAction method when invoked
m_MyEvent.AddListener(MyAction);

代码示例:

 btn.onClick.AddListener(Attack);

您不应添加括号,而应仅使用应调用的函数名称替换Lambda表达式

Unity Documentation