- Home /
C# equivalent of a while loop outside of functions?
How do i convert this code to C#?
#pragma strict
var player : Transform; var speed : float = 5;
while(true) yield CoUpdate();
function CoUpdate() {
if (Input.GetKey(KeyCode.RightArrow)) yield Move(Vector3.right);
else if (Input.GetKey(KeyCode.LeftArrow)) yield Move(Vector3.left);
else if (Input.GetKey(KeyCode.UpArrow)) yield Move(Vector3.forward);
else if (Input.GetKey(KeyCode.DownArrow)) yield Move(Vector3.back);
else yield; }
function Move(distance : Vector3) {
var pt = player.transform;
var goal = pt.position + distance;
while (pt.position != goal) {
pt.position = Vector3.MoveTowards(pt.position, goal, speed * Time.deltaTime);
yield;
}
}
You... shouldn't. This code makes my brain cry a little.
An "always-on" coroutine has only one purpose, AFAI$$anonymous$$: inserting waits into an otherwise always-on, every-frame function. Since that isn't being done here, this approach serves no useful purpose.
Just check your input in Update() and...
change the while-not-at-goal block to an if() and put that in Update() too.
An always-on coroutine in C#:
void Awake() { StartCoroutine($$anonymous$$yRoutine()); }
IEnumerator $$anonymous$$yRoutine() {
// do something
// optional waits or conditions
StartCoroutine($$anonymous$$yRoutine());
}
I've never considered anything like that. Wouldn't it Stack Overflow? @AlwaysSunny
Youtube Link Sir this is the exact movement that the JS code above does. How do i code it in C#?
Your answer
Follow this Question
Related Questions
is not a member of 'UnityEngine.Component' 1 Answer
Convert C# to JS 0 Answers
How do I rotate an object along a curved path if I have a radius in unity3d? 1 Answer
getting a variable from a c# script with a Js 2 Answers
NullReferenceException: Object reference not set to an instance of an object 1 Answer