- Home /
How to change sprites based on score, with a dissolve ?
For every addition of 50 to the score, I want the background sprite to change to a different one by fading with a dissolve. Does it have to be something like an 'if' statement, for every 50, 100, 150, 200, etc score that I have to animate the alpha over time to make it look like a dissolve ? How is something like that achieved ?
Answer by sedativechunk · Jun 07, 2014 at 09:05 PM
You are correct, typically you want to access the alpha channel of the material of the object you are trying to fade in/out (or "dissolve" rather). I'm not sure this will work but your code might want to look something like this: // In your class, set up some variables to handle your scoring int oldScore, newScore; int multiplier = 2; bool fadeOut = false;
void Update()
{
// let's assume you got some basic logic to determine when the score is increased
// When someone does something to win points, track them in the new score
newScore = oldScore;
newScore += points;
if (newScore >= (oldScore * multiplier))
fadeOut = true;
oldScore = newScore;
}
void FixedUpdate()
{
// Get the starting color of your sprite
Color currentColor = this.renderer.spriteRenderer.color.a;
// Set up a speed variable to control how fast you want the fading to be
float dissolveSpeed = 0.3f;
// Fade the alpha on the new color variable we created
// Even when fading colors, it's a good idea to multiply them by delta time, there are other ways to accomplish this though
// reset the fadeout when the alpha is zero
if (fadeOut)
{
currentColor.a -= dissolveSpeed * Time.deltaTime;
if (currentColor.a <= 0)
fadeOut = false;
}
// Lastly set the color back to the new color with the alpha difference (you really only need to store a new variable if you are working in C# as you cannot directly modify the alpha in C#)
this.rendered.spriteRenderer.color = currentColor;
}
I hope that steers you in the right direction.