Ive been trying to program a simple infinite loop in C# that forces a game object to move up until it reaches 3f, then down until it reaches -1f, then up again. I want it to repeat infinitely until I destroy the gameobject. I've tried a couple things like if statements and coroutines but I'm not sure if I am implementing them correctly.
Here are my attempts:
Chained functions:
void MoveUp()
{
transform.Translate(new Vector3 (0.0f, 0.05f, 0.0f));
if (transform.position.y >= 3f)
{
print ("movedown");
MoveDown();
}
}
void MoveDown()
{
transform.Translate(new Vector3 (0.0f, -0.05f, 0.0f));
if (transform.position.y <= -1f)
{
print ("moveup");
MoveUp();
}
}
Coroutines:
void Start ()
{
StartCoroutine(MoveUp());
}
public IEnumerator MoveUp()
{
yield return new WaitForSeconds(1f);
transform.Translate(new Vector3 (0.0f, 0.05f, 0.0f));
if (transform.position.y >= 3f)
{
yield return StartCoroutine(MoveDown());
}
}
public IEnumerator MoveDown()
{
yield return new WaitForSeconds(1f)
transform.Translate(new Vector3 (0.0f, -0.05f, 0.0f));
if (transform.position.y <= -1f)
{
yield return StartCoroutine(MoveUp());
}
}
Any help would be much appreciated!
↧