c# - 为什么我的 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");
}
它不再起作用了..我做错了什么?
解决方案
您应该如何将方法添加到侦听器:
//Add a listener to the new Event. Calls MyAction method when invoked
m_MyEvent.AddListener(MyAction);
您的代码示例:
btn.onClick.AddListener(Attack);
您不应该添加括号以及替换您的 Lambda 表达式,只需使用应该调用的函数的名称
推荐阅读
- ios - 对不包括元素的数组进行排序
- centos - 在 Centos 7 中安装 OpenStack PackStack
- excel - 选择每个工作表中窗格被冻结的单元格
- laravel - 如何在 laravel 5.5 中添加日期函数?
- angularjs - 在 X 上关闭引导程序时清除队列
- aws-lambda - 验证用户输入
- linux - 用linux文件中的字符串替换字符串模式
- javascript - 如何获取对象的属性名称并在 javascript 中使用该属性名称
- reactjs - You may need an appropriate loader to handle this file type.
- ssl - 如果我要反向代理子域,我应该使用什么 SSL 证书?