Fading Sprite

Hi,
I already read every single thread about this topic, but I can’t really figure out the solution.

I want a sprite (a kind of path) to gradually fade to a 0 alpha value while the player is over this sprite for a maximum fixed time.
The problem is that the path doesn’t gradually fade, and when the countdown is over, the alpha value of the sprite is suddently set to 130 (almost half of the full value).

This is the script attached to my fading sprite:

using System.Collections.Generic;
using UnityEngine;

public class FadingPath : MonoBehaviour {

    public float countdownTime; // Time remaining before disappearing
    public MovePlayer player; // Player

    private Color tmpColor; // Color used to fix the new alpha
    private SpriteRenderer sr; // SpriteRenderer component of the fading object
    private float startingTime; // Total passable time over the fading object

    void Start(){
        sr = GetComponent<SpriteRenderer> (); // Access to the SpriteRenderer component
        startingTime = countdownTime;
    }

    void FixedUpdate(){
        if (player.IsOnPath () && countdownTime>0) {
            // New alpha value for fading
            float alpha = 255 / startingTime * countdownTime;

            // Assigning the new alpha value to the SpriteRenderer Color
            tmpColor = sr.color;
            tmpColor.a = alpha;
            sr.color = tmpColor;

            // Decreasing time
            countdownTime -= Time.deltaTime;
        }
    }
}

Sorry if I didn’t explain the problem well, if you need further information I’ll be glad to give them to you.

Thanks in advance and have a nice day!

Color has values from 0 to 1, not 255…

1 Like

@fronzu

@LeftyRighty is right, use 0-1 range when using Color, but if you really like/have to work with 0-255 values, there is Color32.

1 Like

Wow, that was easy! The 0-1 range is not really a problem and it works great now, thanks guys :smile: