Enabling Sprite Renderer in C#

Hi! I’m looking for the simplest way to turn on/off a sprite renderer in C#, I have looked at tutorials and unfortunately found myself with more questions than answers. All I need is for a button to be pressed, and have a sprite appear, I tried deactivating the whole object but that obviously stopped it from turning back on. Any help is greatly appreciated, thank you.

Firstly, your script needs a reference to a sprite renderer. The first step to doing that is to declare this field in your script:

public SpriteRenderer spriteRenderer;

To assign the SpriteRenderer component to this field, you can either link the renderer component to your script in the Inspector (details here and here), or you can use GetComponent when the script initializes:

void Start()
{
	this.spriteRenderer = GetComponent<SpriteRenderer>();
}

Now that you have a reference to the SpriteRenderer component, whenever you need to turn the renderer on or off, you can use spriteRenderer.enabled to set whether it’s enabled or disabled:

this.spriteRenderer.enabled = true; // enable the renderer
this.spriteRenderer.enabled = false; // disable the renderer