Color.lerp for Spriterender is not smooth
The script below works, but it does not fade, it just jumps straight to the color.
using UnityEngine;
using System.Collections;
public class Ladder : MonoBehaviour {
public float smooth = 50;
public Color transparent = new Color(1f,1f,1f,0f);
public Color visible = new Color(1f,1f,1f,1f);
public SpriteRenderer fadeimage;
public GameObject boy;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other)
{
StartCoroutine ("fade");
boy.transform.position = new Vector2 (8f, 11f);
}
public IEnumerator fade(){
fadeimage.color = Color.Lerp (transparent, visible,Time.deltaTime * smooth);
yield return new WaitForSeconds (1);
fadeimage.color = Color.Lerp (visible, transparent,Time.deltaTime * smooth);
}
}
How can I make it fade? Thanks in advance! :)
Answer by darthtelle · Aug 31, 2015 at 01:15 PM
I'm not sure if you fully understand how lerping and coroutines work. A lerp is something which can happen over a period of time between the values (percentages) of 0 and 1. Unity tutorial link. Your coroutine doesn't update anything for an entire second. Coroutines can BASICALLY behave like a second Update() function or a secondary thread. Unity tutorial link.
private IEnumerator Update_Fade()
{
float timer = 0.0f;
float time = 1.0f;
while(timer <= time)
{
timer += Time.deltaTime;
float lerp_Percentage = timer / time;
fadeimage.color = Color.Lerp(transparent, visible, lerp_Percentage);
yield return null;
}
}
I wasn't actually going to write you a solution, because I believe you need to understand first how both methods work, but I hope you won't just copy and paste the answer but actually take the time to understand what's happening. Because this type of function is something I personally use EVERYWHERE. But to do so, you need to understand! :) Hope it helps!
Thank you for your detailed response. I will work on it soon and get back to you :-)
Thanks! it works! But don't worry, I didn't just copy and paste. in fact I learned a lot from your info. Accepted!
@Nsingh13 Brilliant! That's what I like to hear!! Glad I could help. :)
Your answer
Follow this Question
Related Questions
Color.Lerp over HP 1 Answer
Changing image color from other object's script (glitch)? 0 Answers
How to animate fog color over time for day night cycle 1 Answer
Animator controller probably messed up, need advice 0 Answers
2D-Platformer wrong jumps 0 Answers