- Home /
Adding Tint to a Sprite
Hi so i want to add a blue tint to a sprite that i have created.. every time this script runs i would like it to get bluer and bluer until health = 0.. making it all blue.. this is my current code:
public class DestroyOnRainContact : MonoBehaviour
{
public Slider healthBar;
public int Health;
public GameObject Character;
void Start()
{
Health = 100;
}
void OnCollisionEnter2D (Collision2D coll)
{
if(coll.gameObject.tag == "Rain")
{
//Destroy (coll.gameObject);
Health -= 10;
}
if (Health == 0)
{
Destroy(gameObject);
}
}
void Update ()
{
if (healthBar.name == "Slider")
{
healthBar.value = Health;
}
}
}
Help would be awesome!! thanks :D
Answer by maccabbe · Jun 25, 2015 at 05:08 AM
Seems like you want to edit the color of the sprite renderer renderer. Get the renderer using GameObject.GetComponent(). From there change the color of the material using SpriteRenderer.color. Since you want your object to get bluer you probably want to start with pure white and go to pure blue, i.e. Color(health/100, health/100, 1, 1)
would change the color linearly from white (1, 1, 1) at 100 health to blue (0, 0, 1) at 0 health.
http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
http://docs.unity3d.com/ScriptReference/SpriteRenderer.html
void OnCollisionEnter2D (Collision2D coll)
{
if(coll.gameObject.tag == "Rain")
{
//Destroy (coll.gameObject);
Health -= 10;
gameObject.GetComponent<SpriteRenderer>().color=new Color(health/100f, health/100f, 1, 1);
}
if (Health == 0)
{
Destroy(gameObject);
}
}
Answer by Rosscoe3 · Jun 25, 2015 at 05:18 AM
Yay that is working pretty well!!! although i am running into this problem.. Some of the Rain particles are turning that color as they collide with themselves :P
You can disable collisions using the Physics settings. For instance, to disable rain/rain collisions make a new layer "Rain". Then go to the Physics2DSettings (edit->Physics2DSettings) and uncheck Rain x Rain in the Layer collision matrix. Finally, change the layer of the rain objects to Rain.
that sort of works.. the rain doesn't turn blue.. but will not collide with any other objects.. and dissapears on contact.. how do i fix this?