Hello!
I want to fade out sprite when I click on it.
So far I have:
public SpriteRenderer sprite;
public float minimum = 1f;
public float maximum = 0f;
public float duration = 5f;
and
float t = Mathf.SmoothStep(minimum,maximum, Time.time / duration);
sprite.color = new Color (1f, 1f, 1f, t);
^attached to click on the sprite. Everything is ok if I click on it instantly after I run my application. But if I wait some time and then click it - it disappears instantly.
I would suggest making a Coroutine for the purpose of “animated” code, like a fading.
See: Unity - Manual: Coroutines for not only info about coroutines but also code to alpha fade just like you want it (you will need to make some changes based on the context of your game and game mechanics).
It’s because you are using the Variable Time.time, which is how long the game has been running since the start. When you wait 5 seconds before clicking, the fade out sequence is already 5 seconds into it. You can solve this a few ways.
// Member variable to hold the time when the user clicked.
private float clickStartTime;
// In your clicked function, store the time:
clickStartTime = Time.time;
// In your fade out function, take the difference
elapsedTime = Time.time - clickStartTime;
float t = Mathf.SmoothStep(minimum,maximum, elapsedTime / duration);
Alternatively, you can use Time.deltaTime and accumulate the elapsedSeconds in a variable, and just use that.