首页 > 解决方案 > 为什么我的 Button 不适用于 Unity 类中的方法?

问题描述

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

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");        
    }

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

标签: c#unity3d

解决方案


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

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

您的代码示例:

 btn.onClick.AddListener(Attack);

您不应该添加括号以及替换您的 Lambda 表达式,只需使用应该调用的函数的名称

统一文档


推荐阅读