问题描述
在Unity场景中,我希望两个对象通过SendMessage进行通信,因此我不必在运行时执行GetComponent。
这是SendMessage调用:
hit.transform.gameObject.SendMessage("OnSelect",SendMessageOptions.RequireReceiver);
在另一个对象(称为Button)上,我有一个具有此功能的脚本:
public void OnSelect()
{
dialogueManager.displayDialogue(this);
}
当我玩游戏时,OnSelect函数可以毫无问题地运行并且可以完成它需要做的所有事情,但是控制台却显示错误消息:“无法调用Button类的OnSelect函数;调用不带参数的函数,但该函数需要1。'
为什么说该函数实际上不需要1个参数,却需要1个参数呢?我想念什么吗?
解决方法
两件事:
-
Unity的按钮类已经包含一个名为“ OnSelect”的函数,该函数确实具有一个参数。您可以将函数重命名为其他https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Selectable.OnSelect.html
-
SendMessageOptions应该是第三个参数,而不是第二个。因此语法应类似于:
hit.transform.gameObject.SendMessage("OnCustomHit",null,SendMessageOptions.RequireReceiver);
https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html