【问题标题】:Error says function requires 1 parameter when it actually requires none错误说函数需要 1 个参数,而实际上它不需要
【发布时间】:2020-09-02 19:11:27
【问题描述】:

在 Unity 场景中,我希望两个对象通过 SendMessage 进行通信,因此我不必在运行时执行 GetComponent。

这里是 SendMessage 调用:

 hit.transform.gameObject.SendMessage("OnSelect", SendMessageOptions.RequireReceiver);

在另一个对象(称为 Button)上,我有一个具有此功能的脚本:

 public void OnSelect()
     {
         dialogueManager.DisplayDialogue(this);
     }

当我玩游戏时,OnSelect 函数运行没有任何问题,并且完成了它需要做的一切,但控制台给我错误“无法调用类按钮的函数 OnSelect;调用不带参数的函数,但函数需要 1。'

为什么它说函数需要 1 个参数,而实际上它不需要参数?我错过了什么吗?

【问题讨论】:

  • 试试去掉SendMessageOptions.RequireReceiver参数,错误还存在吗?
  • @Bingostew 是的,如果我放置 DontRequireReceiver 和完全删除参数,它仍然存在
  • 那你能把Button的全班贴出来吗?
  • so I don't have to do GetComponent at runtime. 请注意,在较新的版本中使用 GetComponent 相当快,因为​​它现在使用哈希 ... 另一方面,SendMessage 将永远慢得多 然后使用GetComponent!为什么?好吧,首先使用字符串总是很慢,然后它被发送到所有附加的MonoBehaviours,并且必须解析那里是否存在相应的方法......你真的应该坚持hit.transform.GetComponent<Button>().OnSelect();并确保你是使用 你的 Button 而不是 UnityEngine.UI.Button

标签: unity3d sendmessage


【解决方案1】:

两件事:

  1. Unity 的按钮类已经包含一个名为“OnSelect”的函数,该函数接受一个参数。您可以将您的函数重命名为不同的名称https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Selectable.OnSelect.html

  2. SendMessageOptions 应该是第三个参数而不是第二个。所以语法应该是这样的: hit.transform.gameObject.SendMessage("OnCustomHit", null, SendMessageOptions.RequireReceiver); https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多