user3649343
user3649343

Reputation: 21

unity3d OnMouseDown function

I am new to Unity3D. I am trying to do a simple thing. But not able to do this. I have a .obj file which is a 3d key file. I do the followings:

  1. Import this key (to assets) in unity3D
  2. Add this key to scene (from assets to hierarchy)
  3. Add a script to this key
  4. Add the OnMouseDown() function to this script as follows -

    void OnMouseDown() 
    {
        Debug.Log ("clicked...");
    }
    

But when I click the key no message is showing in console. Please tell me what is the problem?

Upvotes: 0

Views: 4547

Answers (4)

Asif Ghaffar
Asif Ghaffar

Reputation: 21

You can also do like by override click function

public override void OnPointerClick(PointerEventData data)
{
    Debug.Log("OnPointerClick called.");
}

Upvotes: 0

Afandi Yusuf
Afandi Yusuf

Reputation: 389

You need to assign a collider to the 3d object if you want to fire it with OnMouseDown:

OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.

This event is sent to all scripts of the Collider or GUIElement.

Upvotes: 0

rygo6
rygo6

Reputation: 2019

The OnMouseDown and it's related functions are all actually older systems. The newer system to use for this is the event system.

Specifically to get mouse clicks you would implement this interface in a class: http://docs.unity3d.com/460/Documentation/ScriptReference/EventSystems.EventTriggerType.PointerClick.html

But there is actually an easier way to do it without code. Using this component: http://docs.unity3d.com/ScriptReference/EventSystems.EventTrigger.html

You can then visually forward the mouse click event to something else.

If you don't fully follow what I have said so far, the thing to really start at is learning the UI system. You can find video tutorials here: http://unity3d.com/learn/tutorials/modules/beginner/ui/ui-canvas

And just to make it clear, the UI system is not just for UI. The UI system runs off an EventSystem which is what you want to use to forward input events to any object 3D or 2D in the entire scene. The UI tutorials will explain the usage of that EventSystem.

Upvotes: 0

hariszaman
hariszaman

Reputation: 8432

  1. make sure the gameobject is not at layer "Ignore Raycast"
  2. Use the following inside your update function to see raycasting is working fine.

    void Update () {

    if (Input.GetMouseButtonDown (0)) {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
               RaycastHit hit;
             if (Physics.Raycast(ray, out hit)) {
              Debug.Log ("Name = " + hit.collider.name);
              Debug.Log ("Tag = " + hit.collider.tag);
              Debug.Log ("Hit Point = " + hit.point);
              Debug.Log ("Object position = " + hit.collider.gameObject.transform.position);
              Debug.Log ("--------------");
             }
           }
    }
    

Upvotes: 2

Related Questions