Make a GameObject changes between 2 colors with a time wait

Hey guys,

I’m making a simple 2D game, I’m stuck at this issue.

There’s a sprite (square) and it moves horizontally in a fixed speed, but the square color is changing between Blue and Red, It start randomly with color lets say it Blue and after some adjustable time from me, ex (5 or 7 seconds) it changes to Red… and so on.

I’m made an array of tow colors and I tired randomize the switching with Random.Rang but the it was too fast and it started like the square is blinking way too fast.
Then I tried to use Coroutine to fix the blinking, but I couldn’t apply it right.

If there’s anyone can help me with this, I would be very thankful…!

Keep in mind, If this works, I’m gonna move to the next thing which will cause another problem:

While the square is moving, if it hits an object (ball or something similar) it will change the current color
randomly, so for example, if the square is Red and it hits the ball it will change either to (Blue) or (Red)–which basically stays the same)

With this code, the squre is jst start with Blue and never changes, if you noticed in the Update method, it started with Red not Blue … What’s happening.

public class MovingMagnet : MonoBehaviour {

    private Rigidbody2D myRigid;
    public float moveSpeed;
    private Collider2D myCollider;
    public GameObject hiddenBox;
    private FixedMagnetSpawner fixedMagnet;
    private SpriteRenderer myRender;


    Color[] colors = new Color[2]; //array of colors

    void Start ()
    {
        myRigid = FindObjectOfType<Rigidbody2D>();
        myCollider = GetComponent<Collider2D>();
        fixedMagnet = FindObjectOfType<FixedMagnetSpawner>();
        myRender = GetComponent<SpriteRenderer>();

        colors[0] = Color.red; 
        colors[1] = Color.blue;
    }

    void Update ()
        {
        myRigid.velocity = new Vector2(moveSpeed, myRigid.velocity.y);
       
            myRender.GetComponent<SpriteRenderer>().color = colors[0];
            //StartCoroutine("TimeWait", 5f);
        myRender.GetComponent<SpriteRenderer>().color = colors[1];
           StartCoroutine("TimeWait", 5f);
    }

    IEnumerator TimeWait(float waitingTime)
    {
        yield return new WaitForSeconds(waitingTime);
    }
 }

public Color lerpedColor = Color.white;
void Update() {
lerpedColor = Color.Lerp(Color.white, Color.black, Mathf.PingPong(Time.time, 1));
}