Translating js to c#

Hey Folks :slight_smile:

recently I’ve been working only with c# so I started “translating” the js scripts of one of my projects into c#. However I’m stuck with this one bit:
JS

function MoveTo(obj: Transform, dest: Vector3, duration: float)
	{
	  if (isMoving) return; // abort call if already moving
	  isMoving = true; // set flag to indicate "I'm moving"
	  var orig: Vector3 = obj.position; // save the initial position
	  var t: float = 0; // start position indicator (0=orig, 1=dest)
	  while (t < 1)
	  	{
			  t += Time.deltaTime / duration; // increment proportionally the indicator
			  obj.position = Vector3.Lerp(orig, dest, t); // set new position
			  yield; // let Unity free until next frame
  		}
  
  		isMoving = false; // clear flag to show the coroutine has ended
	}

and here my C# version

void MoveTo(Transform obj,Vector3 dest, float duration)
    {
        if (isMoving) return;// abort call if already moving
	    isMoving = true; // set flag to indicate "I'm moving"
	    Vector3 orig = obj.position; // save the initial position
	    float t = 0.0f; // start position indicator (0=orig, 1=dest)
	    while (t < 1.0f)
	    {
			t += Time.deltaTime / duration; // increment proportionally the indicator
			obj.position = Vector3.Lerp(orig, dest, t); // set new position
            yield return null;
  	    }
  	    isMoving = false; // clear flag to show the coroutine has ended
    }

I receive this error message: error CS1624: The body of PlayerControlls.MoveTo(UnityEngine.Transform, UnityEngine.Vector3, float)' cannot be an iterator block because void’ is not an iterator interface type

I tried to replace the “yield” with a function that acts as a co-routine. but that only cause the object to move as fast as possible into the direction that is fed into the initial function (dest).

Does any of you guys have a suggestion on how I can solve ths issue ?

Cheers!

Dwnreaver

Instead of “void MoveTo”, “IEnumerator MoveTo” is needed at the beginning.

Yes I tried that before ( and again just to make sure) but the object is still not moving. This is the code I feed into “void MoveTo”:

MoveTo(transform, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), moveTime);

You want MoveTo to be a coroutine. That means, you can’t just call it. You need to start it with

StartCoroutine (MoveTo (...));

Cheers! That worked a treat :slight_smile: Would you be able to explain why it worked in JS but not in C# ? I just would like to understand it.

It’s an ugly behaviour of Unity’s JavaScript. It automatically performs StartCoroutine to make it look easier I guess. But after all, everyone who codes should understand what is going one and explicitly use StartCoroutine. Though, that’s just my opinion. It often produces more confusion than making it simpler.