Skip to main content
Stuff

Introduction to C# in Unity3D #10: While Loops ➿

By February 14, 2021No Comments
While Loop
➿A while loop will execute till the condition is true. If the condition false, the program will exit from the loop. The while keyword will be used
➿The syntax for a while loop is:
while (condition) {  
//code to be executed
}
➿While loops whose condition never evaluates to false are known as infinite loops
➿The condition never evaluates to false therefore the while loop will execute infinitely. So make sure your conditional becomes false at some point in time. For example have a look at the code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CubeController: MonoBehaviour
{
    int num = 1;
    // Start is called before the first frame update
    void Start()
    {
        while (num < 5)
        {
            Debug.Log("The value of num is " + num);
            num++;
        }
        Debug.Log("Exited the while loop");
    }

    // Update is called once per frame
    void Update()
    {


    }
}

Leave a Reply