Beginner Scripting: Loops


This weeks Coding Task was the most confusing one by far. I'm not sure if I came across loops in the last semester or used them in my coding before but this seemed like a new code that I hadn't come across yet. It was good to see examples of the code and how it worked but it still seems a little unclear. I will need to see it in action in a game and the appropriate way to use it then. For now it is good to be aware of it and see how there are different ways to loop. Code is as follows:

ForLoop

public class ForLoop : MonoBehaviour { int numEnemies = 3; void Start () { for(int i = 0; i < numEnemies; i++) { Debug.Log("Creating enemy number: " + i); } } }

WhileLoop

public class WhileLoop : MonoBehaviour { int cupsInTheSink = 4; void Start () { while(cupsInTheSink > 0) { Debug.Log ("I've washed a cup!"); cupsInTheSink--; } } }

DoWhileLoop

public class DoWhileLoop : MonoBehaviour { void Start() { bool shouldContinue = false; do { print ("Hello World"); }while(shouldContinue == true); } }

ForeachLoop

public class ForeachLoop : MonoBehaviour { void Start () { string[] strings = new string[3]; strings[0] = "First string"; strings[1] = "Second string"; strings[2] = "Third string"; foreach(string item in strings) { print (item); } } }

Comments

Popular Posts