Iterating through RaycastHit2D[] to find highest transform.y?

Hi all,

This question betrays me as a beginner. I am currently trying to do something relatively simple - I am using RaycastAll to return an array of hit, and I then wish to select the hit that contains the collider with the greatest transform.position.y value (and that also is tagged with the value “Node”). The following code accomplishes this:

RaycastHit2D[] hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
RaycastHit2D selectedHit = hits[0];
bool hitSelected = false;
foreach (var hit in hits)
{
    if (hit.collider != null)
    {
        if (hit.collider.tag == "Node")
        {
                if (!hitSelected)
            {
                selectedHit = hit;
                hitSelected = true;
            } else
            {
                if (hit.collider.transform.position.y > selectedHit.transform.position.y)
                {
                    selectedHit = hit;
                }
            }
                        
        }
    }
}

However, I can’t help but feel that this is a bit hackish. Is there a cleaner, more acceptable way of accomplishing this?

// Consider storing Camera.main into a variable you initialize in the Start method
RaycastHit2D hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
RaycastHit2D? selectedHit = null;

foreach (var hit in hits)
{
    Collider collider = hit.collider;
    if (collider != null && collider.CompareTag("Node"))
    {
        if (selectedHit.HasValue == false || collider.transform.position.y > selectedHit.Value.transform.position.y)
        {
            selectedHit = hit;
        }
    }
}

// Consider storing `Camera.main` into a variable you initialize in the `Start` method
RaycastHit2D[] hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hits.Length > 0)
{
    RaycastHit2D selectedHit = hits[0];

    for(int i = 1 ; i < hits.Length ; ++i)
    {
        Collider collider = hits*.collider;*

if (collider != null && collider.CompareTag(“Node”) && collider.transform.position.y > selectedHit.transform.position.y)
{
selectedHit = hits*;*
}
}
}