2
votes

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.

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?

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
sure, use Unity Events - you've exactly described them. Just click to the manual or a billion QA or tutorials - Fattie
I'm voting to close this question as off-topic because full information instantly available at the manual unity3d.com/learn/tutorials/modules/intermediate/scripting/… Also check out forum.unity3d.com/threads/… - Fattie
just BTW if you are touching/inputting, this is like the fundamental, overwhelming problem in unity: answers.unity3d.com/questions/784617/… - Fattie
@JoeBlow So how do I attach it to the pre-exsisting event that triggers OnMouseDown? Because I don't want to have to create additional scripts on objects to trigger such events. The video you linked describes how to craete an event / delegate system, I don't want to create a new one, I want to attach a callback to a pre-exsisting unity event trigger for that object, and that is what I don't understand..? - Zze
inside the relevant OnMouseDown, just more.Invoke, and drag anything you want to more which is a public UnityEvent. it's "less than" one line of code, you just drag. - Fattie

1 Answers

2
votes

1) I understand the sense of what you mean by this

pseudocode:
gameObjectReference.GetComponent<BoxCollider>().onmousedownevent += MyFunction

and there is no way to do that.

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 constantly

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.