jason
jason

Reputation: 3615

Unity3D prevent clashes with mouse events

I am new to Unity3D. I have a scene composed of a number of objects:

  1. A prefab that makes a room (mesh plane for the floor, 4 mesh planes for the walls). Each of these has a Mesh Collider

  2. Canvas with a number of UI elements

  3. Inside the prefab room I created a table, comprised of a Cylinder (for the table base), a cube for the table top, four cubes that create walls around the edge of the table top to give it a lip, and on the table top is a plane (this is the table "felt" and also has a box collider and Rigid Body). These all have Colliders. This is all made into a prefab.

  4. On the table top I have some prefab cubes (dice). These have a rigid body and collider.

The problem I am having is that the mouse events do not register for the dice (they have a script attached). On the Update event, I have this code:

 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("--------------");
            }
        }

I can see that even though I click on the dice, other objects are getting in the way (ie. the walls of the room, the table walls, table top, etc.).

So, how do I over come this? Other than the UI elements, the only objects that need to have mouse events are the dice. Is there some way to not register mouse events for everything else? Oh, and I'm writing this in C# and this is a 3D project.

thanks

here you can see the result of clicking on the dice.  It registers the TableBase.  If I move the dice up, away from the table, where the back wall is behind the dice, then the back wall will be registered

Upvotes: 3

Views: 173

Answers (1)

Dávid Florek
Dávid Florek

Reputation: 571

Put the dice on different layer and use layermask with your Raycast. Here is the documentation.

Upvotes: 1

Related Questions