Javascript 2D change color of spriteRenderer through script
I've got a sprite in Unity 2D that I want to change colors when I press a button
if(Input.GetKeyDown("w")){
if(perka == 0){
renderer.material.SetColor("_Color", Color.red);
perka = 1;
}else{
renderer.material.SetColor("_Color", Color.blue);
perka = 0;
}
}
It told me renderer.material.SetColor("_Color", Color.blue); is obsolete, & every answer I've found is either in C# or gives an error in the console. The manual was no help either
The only one I've found that doesn't bring up an error is
GetComponent(SpriteRenderer).color.a = 5.0;
& it's closer to what I want, because I'd rather be able to control color as a number than be restricted to the base terms of the color wheel. But this code does absolutely nothing to my 2D SpriteRenderer. I suspect it's meant for a 3d material, but does anyone know how to create this type of code for a 2D SpriteRenderer? I appreciate any help
Answer by Hellium · Oct 22, 2017 at 08:41 AM
Keep in mind that color values are clamped between 0 and 1.
var renderer : SpriteRenderer = gameObject.GetComponent(SpriteRenderer) as SpriteRenderer;
var color : Color = renderer.color ;
color.a = 0 ;
renderer.color = color ;