How To Make Something Happen Every 0.5 Seconds While Key is Pressed

I’m experimenting with sprite Sheets and I don’t know how to offset my texture every say… 0.5 of a second while a key is pressed down. This is my script, I’m trying to print “hi” every 0.5 of a second but is doesn’t work:

function Update(){
     if(Input.GetAxis("left/right") > 0){     //if right key is pressed
          Animate();
     }
}

function Animate(){
     yield WaitForSeconds(0.5);
     print("hi");
}

Can someone help me out?

Thanks

One way to go about:

function Update() {
    var isMoving = Input.GetAxis("Horizontal") > 0; 
    if (isMoving && !IsInvoking("Animate"))
        Invoke("Animate", 0.5f);
}

function Animate() {
    print("hi");
}

Another way to go about:

while (true) {
    var isMoving = Input.GetAxis("Horizontal") > 0; 
    if (isMoving)
        yield Animate();
}

function Animate() {
    yield WaitForSeconds(0.5f);
    print("hi");
}

function Update () {
if (Input.GetKeyDown(KeyCode.RightArrow)) {
InvokeRepeating(“Animate”, .01, .5);
}
if (Input.GetKeyUp(KeyCode.RightArrow)) {
CancelInvoke(“Animate”);
}
}

function Animate () {
	// whatever
}

Hi

I hope this will help you.

public IEnumerator DoSomeThing()
{
    yield return new StartCoroutine("Tick");
}

public IEnumerator  Tick()
{
    Debug.Log("Hi");
    yield return new WaitForSeconds(0.5f);   
}

public void Update()
{  
    if(Input.GetAxis("left/right") > 0)
    {     
        DoSomeThing();       //if right key is pressed
    }
}

Regards

Laksh