Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 299
jason Avatar asked Sep 17 '26 04:09

jason


1 Answers

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

like image 171
Dávid Florek Avatar answered Sep 18 '26 18:09

Dávid Florek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!