Coroutine loop not working?

Updated on February 26, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on February 26, 2017

Hey all. I’m trying to Lerp with a coroutine and I’m seeing what I think I should be.

Here’s a snippet of the necessary code:

 IEnumerator RaiseUp (Vector3 endPos){  //given a position about 5 units more in the y direction than startPos (below)
  
  GameObject blueCube = GameObject.FindGameObjectWithTag("BlueCube");
  Vector3 startPos = blueCube.transform.position;
  
  int numFramesToGo = 1000; //say it's 1000 frames for simplicity
  int timeToGo = numFramesToGo * Time.deltaTime; //approximation which returns a reasonable   number like 20 seconds
  
  for (int i = 0; i < numFramesToGo; i++)
  {
    int percent = i / numFramesToGo;
    Debug.Log("percent: " + percent);
    blueCube.transform.position = Vector3.Lerp(startPos, endPos, percent);
    // yield return new WaitForEndOfFrame(); //tried this, didn't work either
    yield return null;
    // wait then repeat
  }
  
 }
 

The problem I seem to be having is that in my debug statement, percent is always ‘0’ for every frame. This means that my cube doesn’t float upwards like I believe it should.

What am I missing here? Am I lerping wrong?

  • Liked by
Reply
0 on February 26, 2017

I’ve tried doing more research into Coroutines already (like this) and all I find is reassurance that my code should be working…

  • Liked by
Reply
Cancel
0 on February 26, 2017

Aw, snap. I think I just figured it out. percent needs to be in float form!

It’s the little things, everyone…

  • Liked by
Reply
Cancel