Quantcast
Channel: Questions in topic: "loops"
Viewing all articles
Browse latest Browse all 184

How to start an infinite loop that cycles between two actions?

$
0
0
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!

Viewing all articles
Browse latest Browse all 184

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>