- Home /
Color.Lerp everytime Onclick
Hello, how can I reset the Lerp in Update to be clear to white color again every time press next button? Thank you.
public class typeText : MonoBehaviour {
private int counter = 0;
public GameObject img;
private bool loop = false;
float speed;
void Update() {
speed += Time.deltaTime;
if (loop) {
img.GetComponent<Image> ().color = Color.Lerp (Color.clear, Color.white, speed * 0.4f); }}
public void next() {
loop = true;
counter++;
img.GetComponent<UnityEngine.UI.Image> ().sprite = Resources.Load<Sprite> (counter);
}
}
Comment
Best Answer
Answer by kleber-swf · Oct 28, 2016 at 01:56 PM
Hi there,
If I understand well, you are trying to create a next button that when you click on it, it loads a sprite from the resources, became transparent and visible again smoothly.
First, please cache your image reference. GetComponent
is not to meant to be called every frame. Consider to change the field img to type Image
or use the GetComponent
in the Start()
method to cache the image reference to another field.
The problem is that you are not resetting speed
code> nor loop
fields.
public class TypeText : MonoBehaviour {
private int counter = 0;
public Image img;
private bool loop = false;
float speed;
void Update() {
if (!loop) return;
speed += Time.deltaTime;
var t = speed * 0.4f;
img.color = Color.Lerp(Color.clear, Color.white, t);
if (t >= 1f) loop = false;
}
public void next() {
loop = true;
speed = 0;
counter++;
img.sprite = Resources.Load<Sprite>(counter);
}
}
Another solution could be create an Animation and use it in the Button
component.