jtth
jtth

Reputation: 886

How do you use OnMouseDown on any object w/o a script attached in Unity?

Hypothetical: You've an empty GameObject called "InputManager" with a script attached that utilizes the OnMouseDown function to return data on an object when it is clicked on.

The problem: The OnMouseDown function only works on objects with the script, containing the function, attached to them.

Question: How do you maneuver this restriction of OnMouseDown only working on objects that a script attached with the function call? (Note: I'm attempting to avoid adding the script to every single object in the scene)

Upvotes: 0

Views: 2490

Answers (1)

KamikyIT
KamikyIT

Reputation: 314

You can try to use Raycast to detect all GameObjects with Colliders.

https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

It will return all the objects being hit and then work with them as simple GameObjects. And then you can send them messages with

https://docs.unity3d.com/ScriptReference/Component.SendMessage.html

without working with you script component.

It will be somethink like:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
    hit.collider.gameObject.SendMessage("BeingMouseClicked");
}

The "BeingMouseClicked" string is just example method name.

Upvotes: 1

Related Questions