Search code examples
c#unity-game-engineraycastinggameobject

Get an list of multiple gameobjects that cross mouse line


Actually I'm using this following code to detect the collision between the mouse and some object.

I want the code to capture multiple GameObjects (not only the first one, but the ones that are above) and store it in a List.

I looked about Physics.RaycastAll but I was a little confused about.

void Update () 
{
    RaycastHit hit;

    Ray ray =  Camera.main.ScreenPointToRay(Input.mousePosition);

    if(Physics.Raycast(ray,out hit))
    {       
        if (hit.collider != null)
        {
            print (hit.transform.gameObject.name);          

        }               
    }
}

Solution

  • There is nothing confusing here. The only difference is that Physics.Raycast returns true or false if something is hit while Physics.RaycastAll returns array of RaycastHit. You just have to loop over that array of RaycastHit.

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    
        RaycastHit[] hit = Physics.RaycastAll(ray);
    
        for (int i = 0; i < hit.Length; i++)
        {
            if (hit[i].collider != null)
            {
                print(hit[i].transform.gameObject.name);
            }
        }
    }
    

    Note:

    It is better to use Physics.RaycastNonAlloc instead of Physics.RaycastAll if you want to detect every Object hit. This will not allocate memory at-all especially when doing this in the Update function.

    //Detect only 10. Can be changed to anything
    RaycastHit[] results = new RaycastHit[10];
    
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    
        int hitCount = Physics.RaycastNonAlloc(ray, results);
    
        for (int i = 0; i < hitCount; i++)
        {
            if (results[i].collider != null)
            {
                print(results[i].transform.gameObject.name);
            }
        }
    }
    

    The code above will detect 10 objects max. You can increase it if you want.