- Home /
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?
There are many ways to script time-based events. Your issue arises because Time.time accumulates. You should research coroutines and Time.deltaTime.
Answer by Wisearn · Nov 14, 2014 at 02:52 PM
I would suggest making a Coroutine for the purpose of "animated" code, like a fading.
See: http://docs.unity3d.com/Manual/Coroutines.html 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).
Thank you! That was the best idea here and it worked like a charm. :)
Answer by Eck · Nov 14, 2014 at 02:59 PM
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
Thank you! I think @Wisearn had a better idea but thank you too. :)
Wow, that co-routine stuff is pretty slick. I've only been messing with Unity for a week or two so I hadn't stumbled across this technique yet. Very cool.
Eck
Answer by SmalleeStudio · Nov 14, 2014 at 02:54 PM
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
Answer by PixelFireXY · Nov 14, 2014 at 03:01 PM
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: http://unity3d.com/learn/tutorials/modules/beginner/scripting/lerp
and what do you need first of all is to follow all these tutorials: http://unity3d.com/learn/tutorials/modules/beginner/scripting
good coding ;)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Fade in/out a GameObject 1 Answer
Smoothly Fade in a texture 1 Answer
How do I make the screen fade when it goes into the next level? 0 Answers
Fade In / Out UI Image 3 Answers