Count objects in a raycast

Hello!
I got a raycast, which I use to detect 2 different objects. Now I want to count, how many objects are in one raycast. That’s my script (or parts of it):

public class RaycastWin : MonoBehaviour {
int rightHitsToWin = 1;

void Update() {
var transformStone = GetComponent();

Vector2 right = transform.TransformDirection(Vector2.right) * 5;

Ray2D rightRay = new Ray2D(new Vector2(transformStone.position.x + 1, transformStone.position.y), right);

RaycastHit2D rightHits = Physics2D.RaycastAll(rightRay.origin, rightRay.direction, 2);

foreach (RaycastHit2D rightHit in rightHits) {

if (gameObject.CompareTag(“orange”)) {

if (rightHit.collider.CompareTag(“orange”)) {

Debug.Log(“HIT! OrangeRight”);

rightHitsToWin++;
}
}

        if (gameObject.CompareTag("blue")) {
            if (rightHit.collider.CompareTag("blue")) {
                Debug.Log("HIT! BlueRight");
                rightHitsToWin++;
            }
        }
    }

    }

}

So, as you see, in my script I count every frame ++ one and the same object. How can I count one object only once?

Thanks in Advance :slight_smile:

I made a version of your script that lists all objects that have the same tag as the object the script is attached to. When a raycast hits one of them, it’s removed from the list so it’s only counted once. (I’m not sure what that transformStone is supposed to be?)

using System.Collections.Generic;

public class RaycastWin : MonoBehaviour
{
    HashSet<GameObject> requiredObjects;
    int rightHitsToWin = 1;

    void Start()
    {
        // Find objects with the same tag as this object
        requiredObjects = new HashSet<GameObject>(GameObject.FindGameObjectsWithTag(tag));
    }

    void Update()
    {
        var transformStone = transform;

        Vector2 right = transform.TransformDirection(Vector2.right) * 5;
        Ray2D rightRay = new Ray2D(new Vector2(transformStone.position.x + 1, transformStone.position.y), right);
        RaycastHit2D[] rightHits = Physics2D.RaycastAll(rightRay.origin, rightRay.direction, 2);

        foreach (RaycastHit2D rightHit in rightHits) {
            if (requiredObjects.Contains(rightHit.transform.gameObject)) {
                Debug.Log("HIT! " + tag + "Right");
                requiredObjects.Remove(rightHit.transform.gameObject);
                rightHitsToWin++;
            }
        }
    }
}