- Home /
The question is answered, right answer was accepted
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.
Answer by Commoble · Apr 20, 2017 at 10:04 PM
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
Side note: This answer assumes your script and spriterenderer are on the same object. If they're on separate objects, GetComponent won't work (unless you have a reference to the other object, in which case you call otherGameObject.GetComponent<SpriteRenderer>()
.
If both objects are in the scene when the scene starts, linking objects via the inspector still works here; you can declare your public SpriteRenderer spriteRenderer;
field and drag the other gameobject to that field, and it'll assign the SpriteRenderer component on that other object to that field.
Thanks Commoble, this worked perfectly :)