Changing color of gameobject over a period of time

I have a gameObject and want to change its color from Green to red and change it back from red to green.

The gameobject’s starting position is (0,-9,0). It will be moving up to the position (0,-6,0) over a period of 1.5 seconds. I want to change its color from green to red during the 1.5 seconds.

The gameobject will move back to its original position after the above movement over another period of 1.5 seconds. (Moves back from (0,-6,0) back to (0,-9,0)). I want to change back its color from red to green during this 1.5 seconds.

The following script is attached to the gameObject. There is no errors and nothing happens. The colors remains unchanged as the default color green. Please advice what I am missing. Thanks.

void Update()
{
    ColorChanger();
}

void ColorChanger()
{
    if (this.tag == "Barrier")
    {
        if (transform.position.y <= -9)
        {
            Color.Lerp(Color.green, Color.red, 1.5f);
        }

        if (transform.position.y >= -6)
        {
            Color.Lerp(Color.red, Color.green, 1.5f);
        }
    }
}

Your code is missing something very important.
Color.Lerp does change the color, but you’re not applying it anywhere,
You should change the renderer.material.color of the GameObject.

Issue 2 is that you are trying to use Color.Lerp which is VERY limiting,
It only works with time.Time, hence it needs a lot of hack in order to work.
My advise is to use Animations, and call the proper animation (that changes the color) when your condition is met. (I can help you with that if you need).

However, i did make your code work. Unfortunately, it is very limiting as i am not able to reset t whenever i want.
You can create an Input.GetButtonDown(“Jump”) for instance and reset t inside of it, but it wouldn’t be as dynamic as you would want it to.

The below code works on your object, however, it only works once as t is not reset to 0

Hope you like the code and it would be of assistance.
Again, I would advise an alternative approach.

using UnityEngine;
using System.Collections;

public class ColorChanger : MonoBehaviour {

	float duration = 1.5f;
	private float t = 0;
	bool isReset = false;

	void Update()
	{
		ColorChangerr();
	}


	void ColorChangerr()
	{
		if (this.tag == "Barrier")
		{

				renderer.material.color = Color.Lerp(Color.green, Color.red, t);

				if (t < 1){ 
					t += Time.deltaTime/duration;
				}
			
		}
			
	}
}

Color.Lerp is a color, it isn’t a method.
You need to assign the value of Color.Lerp to your renderer if you want a change to appear.

For example :
renderer.material.color=Color.Lerp(Color.green, Color.red, 1.5f);

You can also serialize the variable at start by writing this :
myMaterial = renderer.material, and then myMaterial.color=Color.Lerp(Color.green, Color.red, 1.5f). It will be faster.