Fade out sprite on click

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.

How can I fix it?

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.

  • Eck

Time.time means The time “since the start of the game”.

So when the time of the game goes 5 second, the vaiue : Time.time / duration = 1

It may disappear instantly

What do you need is to follow some unity tutorials to learn the basics of coding in unity.

What do you need for your code is this video: Unity Connect

and what do you need first of all is to follow all these tutorials:

good coding :wink: