Make 2d sprites invisible?

I’m trying to make most of the sprites in my game invisible. With the exception of a few that are tagged “Player”, “Background” “Ground”.

I tried this

if(!gameObject.CompareTag("Player"))
{
 gameObject.renderer.enabled= false;
}

But I get an error about the renderer missing.

Maybe this?

    if(!gameObject.CompareTag("Player"))
    {
     if(gameObject.renderer != null)
     {
       gameObject.renderer.enabled= false;
     }
    }

You need to get the component of the gameObject and then turn the SpriteRenderer off.

public SpriteRenderer sprender;


void turnOff() {
   if(!gameObject.CompareTag("Player"))
    {
    sprender = gameObject.GetComponent<SpriteRenderer>();
    sprender.enabled= false;
    }
}