本文介绍了Unity - 添加回调到 GameObject OnMouseDown 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 目前,当我尝试检测对象是否已被鼠标单击/交互时,我在该游戏对象上创建了一个脚本,然后定义 void OnMouseDown() 并在其中应用功能.如果我想在另一个未附加到游戏对象的脚本中触发一个函数,我会通过 GetComponent() 引用调用它.Currently when I am trying to detect whether an object has been clicked / interacted with by the mouse, I create a script on that GameObject and then define void OnMouseDown() and apply functionality within. If I then want to trigger a function in another script that is not attached to the GameObject I call it through a GetComponent<>() reference.有没有办法从另一个游戏对象上的脚本向 OnMouseDown 事件添加回调?可能以相同的方式分配和调用委托/事件?例如:gameObjectReference.GetComponent().onmousedownevent += MyFunction; 这样它会在鼠标按下时自动调用这个函数吗?Is there a way to add a callback to the OnMouseDown event from a script on another GameObject? Potentially in the same way delegates / events are allocated and invoked? Something such as: gameObjectReference.GetComponent<BoxCollider>().onmousedownevent += MyFunction; So that it automatically calls this function on mouse down?注意:我知道您可以使用光线投射来实现类似的效果,但我的问题是将回调附加到现有的 Unity 事件.Note: I know that you can use raycasting to achieve something similar, but my question is about attaching callbacks to the existing Unity event.推荐答案1) 我明白你的意思pseudocode:gameObjectReference.GetComponent<BoxCollider>().onmousedownevent += MyFunction没有办法做到这一点.2) 请理解:实现您的目标非常容易(优雅地).在脚本b"中添加一个 UnityEvent,在 OnMouseDown 中调用它.将任何你想要的东西拖到那里.对于任何刚接触 Unity 的读者,请尝试使用 UnityEvent,因为它经常被使用2) please do understand: it is incredibly easy to achieve your aim (elegantly). Add a UnityEvent in script "b", Invoke it in the OnMouseDown. drag anything you want there. For anyone reading who is new to Unity, pls try UnityEvent in general as it is used constantly3) AI 提到你可以某种通过玩弄OnPointerDown(PointerEventData eventData)系统来做你想做的事,但这只是强调你不能做你问什么,就用 OnMouseDown 来做.3) A I mention you can kind of do what you want by fooling around with the OnPointerDown(PointerEventData eventData) systems, but this just emphasises you can't do what you ask, do it with OnMouseDown.对于这个严峻的消息感到抱歉.Sorry for the grim news. 这篇关于Unity - 添加回调到 GameObject OnMouseDown 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-15 11:19