-1
\$\begingroup\$

I want to loop between two color in unity

public float speed = 1.0f;
public Color startColor;
public Color endColor;
public bool repeatable = false;
float startTime;

// Use this for initialization
void Start()
{
    startTime = Time.time;
}

// Update is called once per frame
void Update()
{
    if (!repeatable)
    {
        float t = (Time.time - startTime) * speed;
        GetComponent<Light>().color = Color.Lerp(startColor, endColor, t);
    }
    else
    {
        float t = (Mathf.Sin(Time.time - startTime) * speed);
        GetComponent<Light>().color = Color.Lerp(startColor, endColor, t);
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ What is your endgoal here? \$\endgroup\$ – Sidar Nov 6 '17 at 20:04
  • \$\begingroup\$ I want to loop between two color red and blue ; \$\endgroup\$ – Kartik Nov 6 '17 at 20:04
  • \$\begingroup\$ You want to ping pong between 2 color values? \$\endgroup\$ – Sidar Nov 6 '17 at 20:05
  • \$\begingroup\$ and my end goal is change the color of point light gradually with time and loop the colors \$\endgroup\$ – Kartik Nov 6 '17 at 20:06
4
\$\begingroup\$

Use Mathf.PingPong to lerp between your colors

private float duration = 5 ;
private Light lightComponent ;

private void Awake()
{
    lightComponent = GetComponent<Light>();
}

void Update()
{
    float t1 = Mathf.PingPong(Time.time - startTime, 1) / duration;
    float t2 = (Mathf.Cos( ( (Time.time - startTime) + duration ) * Mathf.PI / duration ) + 1 ) * 0.5f

    // Use t2 instead of t1 if you want smoother interpolation
    lightComponent.color = Color.Lerp(startColor, endColor, t1);
}

Desmos plot showing t2

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.