I was trying to solve a similar problem on my project and ended up with this workaround solution. I’m not sure if it’s the best, but it seems to get the job done.
The key here is that one of the overload methods for Physics2D.Raycast lets you output an array or list of results instead of just getting the first hit. Then you can check through your results list and find the one that matches the game object you’re checking against.
List<RaycastHit2D> resultsList = new List<RaycastHit2D>();
Physics2D.Raycast(raycastStart, raycastDirection, contactFilter, resultsList, rayCheckDist);
foreach (RaycastHit2D result in resultsList)
{
Debug.Log(result.collider.gameObject);
if (result.collider.gameObject == gameObjectToCheckFor)
{whatever you want to happen here}
}