Sprite Color Change upon collision

Hey everyone I have a problem. I tried many different methods to access the sprite’s color and change it upon collision. Nothing I tried is working

I tried the following

GetComponent().color = Color.red;

SpriteRenderer renderer = GetComponent();
renderer.color = new Color(0.5f, 0.5f, 0.5f, 1f);

The code I have is when the numberofhits equal a certain number it becomes that color, but I need to access the sprite Renderer to change the color.

Below is my function:

void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "BlueBlock")
        {
            if (numberOfHits == 1)
            {
                SpriteRenderer renderer = GetComponent<SpriteRenderer>();
                renderer.color = new Color(0.5f, 0.5f, 0.5f, 1f); // Set to opaque gray
            }

        }
    }

Hello KG3,

I was facing the same issue when trying to build a block breaker game. In which should change the color of the game object on collision (different blocks should be hit different times before destroyed). Here’s the solution I’ve found:

public class Brick : MonoBehaviour {
    public int life;
       
    void OnCollisionEnter2D(Collision2D collision)
    {
        life--;
        if (life == 2)
        {
            GetComponent<SpriteRenderer>().color = new Color(1f,0.30196078f, 0.30196078f);
        }

        if (life == 1)
        {
            GetComponent<SpriteRenderer>().color = new Color(0.388235229f, 0.3372549f, 1f);
        }
        
        if (life <=0)
        {
            Destroy(gameObject);
        }

    }

    
}

I hope it helps.