Find out sprite of an object my raycast hit

Hi! I asked this question before but it seemed to buggy or something, so I post it here again:

I have a raycast which goes through different objects. They all are one gameobject created from a prefab, but with two different sprites in my sprite renderer. I want to find out, which sprite the object hit by my raycast has on it. What is the best way to do that? :slight_smile:

The raycasting functions return a struct which contains data about what the ray hit. You can use this to access components on the object that was hit, including the sprite. In your script, set up some references to the two sprites you care about:

public Sprite yourSprite1; // Hook these up in the inspector, or load them from Resources.
public Sprite yourSprite2;

Then, in whatever method you do your raycasting:

Ray myRay = /* Code that specifies your ray goes here. */ ;
RaycastHit[] hits = RaycastAll(myRay);

foreach (RaycastHit hit in hits) {
    SpriteRenderer spriteRenderer = hit.collider.GetComponent<SpriteRenderer>();
    
    if (spriteRenderer != null) {
        if (spriteRenderer.sprite == yourSprite1)
            // Do something.
        else if (spriteRenderer.sprite == yourSprite2)
            // Do something else.
    }
}