Raycast to multiple objects

Hello everyone, I’m here because I’ve been stuck on a problem for the whole day.
My problem is simple (I guess) but I cannot figure it out: I’m in a 3d enviroment and I have an amount of objects (simple cubes with a Box Collider attached on them), I need to check if the cursor is pointing to one of those cubes and, if so, which of them. I need to retrieve the GameObject of the collider which has been hit by the Raycast so I can perform various operations on it.

In the first place I tried using an array of cubes and using the collider’s Raycast method to check which cube was hit, like the following code:

foreach(GameObject cube in carCubes) {
       RaycastHit cubeHit;
       BoxCollider box = cube.GetComponent<BoxCollider>();
       if (box.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out cubeHit,100f)) {
               //cube was hit

But then I figured out this wasn’t the solution since this algorithm does not consider the order of appearance of those cubes and so if, from the camera’s point of view, there was multiple cubes overlapped, it could find as the first hit a cube on the back.

So I moved to the following code:

if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit, 100f) {

But now I cannot figure out which cube was hit by the raycast and that information is crucial because I need to know which face of the cube has been hit with the cursor. So the problem is: how can I get which face of the cube and which cube has been hit ?

I know the problem may be very easy to solve, but I’m still a beginner and I couldn’t find out a working solution.


using Physics.RaycastAll instead might help you out http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html

it returns an Array of everything hit so you can loop through for whatever you want.

I figured out a way to do it.
I didn’t notice RaycastHit has a propriety called Transform which returns the transform of the Collider that has been hit.
So I used
RaycastHit hit;

//r is a Ray from the mouse position
if (Physics.Raycast(r,out hit, 100f) {
    Transform cube = hit.transform; //cube is the object
    // Other stuff...

I used RaycastHit.normal to calculate which face was hit.