Change image color gradually on click

i want to change gradually a background from white to red when i click a button but can’t figure it out how to do. I was thinking to use Color.Lerp but the problem is that i cant make the “t” to change slowly from 0 to 1. any ideias? I want run this when the player have less money than the price of what he is trying to buy. Thanks.

You can use coroutines to achieve this. The following coroutine will gradually change the color of the given image over specified duration:

private IEnumerator ChangeColor(Image image, Color from, Color to, float duration)
	{
		float timeElapsed = 0.0f;
		
		float t = 0.0f;
		while(t < 1.0f)
		{
			timeElapsed += Time.deltaTime;

			t = timeElapsed / duration;

			image.color = Color.Lerp(from, to, t);
			
			yield return null;
		}
	}

To start coroutine use:

StartCoroutine(ChangeColor(image, Color.blue, Color.red, 3f));

It will change the color from Blue to Red over 3 seconds.

Performance note: The code above will update the color on every frame. If you want to do it less frequently, one way to do it would be to replace the yield instruction with WaitForSeconds(updateInterval) and update the timeElapsed calculation accordingly.