- Home /
Toggling a sprite renderer?
I need to be able to turn a sprite renderer on and off for my player hurt effect. The title mostly says it all.
So, how do I toggle the sprite renderer on an object from a script?
Oh, and if this changes anything, I want to do it in c#.
Answer by _joe_ · Apr 07, 2015 at 12:55 AM
Here's a code using a C# coroutine.
You can copy the code you need to make it longer, and change the wait for second to make it faster or slower. Also make it cleaner by saving the renderer in a variable, Allow the Coroutine to take an argument (probably the delay), so you can control the speed of the flickering.
void Start(){
StartCoroutine("ToggleRenderer");
}
IEnumerator ToggleRenderer(){
yield return new WaitForSeconds(0.5f);
this.gameObject.GetComponent<SpriteRenderer>().enabled = false;
yield return new WaitForSeconds(0.5f);
this.gameObject.GetComponent<SpriteRenderer>().enabled = true;
yield return new WaitForSeconds(0.5f);
this.gameObject.GetComponent<SpriteRenderer>().enabled = false;
yield return new WaitForSeconds(0.5f);
this.gameObject.GetComponent<SpriteRenderer>().enabled = true;
//Repeat as much as needed
}
You never have to use this.gameObject. 'this' is redundant. When talking about the object that the script is attached to, you never have to specify. You can just use the methods out of thin air.
GetComponent<SpriteRenderer>().enabled = true;
Also, StartCoroutine using a string method name allows you to use StopCoroutine with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter. For this example it is better to use:
StartCoroutine(ToggleRenderer());
Answer by MariBR · Jan 03, 2016 at 05:53 PM
Another suggestion: Change object, eg.: when the player dies.
void Die()
{
manager.deadPlayer = true;
Instantiate (playerDead, transform.position, Quaternion.identity);
Destroy (gameObject);
}
Know this package: https://www.assetstore.unity3d.com/en/#!/content/48654
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why is my character selection menu not working. 1 Answer
How can I change the Value of a Color through script? 1 Answer
Sprite Swapping help 1 Answer