Nerd For Tech
Published in

Nerd For Tech

What are While Loops

While loops within C# provides us to repeatedly execute a block of code as long as the specified conditions are met. Once the requirements of the code block is false, it will not run the loop.
When making a while loop, more often then not, you will see them within a coroutine. This is because it allows our coroutines process the continuously run until we don’t meet the requirements anymore. However, a key aspect to remember when running the routine is to not get it stuck in an infinite loop:

With a while loop as such, our routine will run forever and crash the program because it has nothing to end on. If we wanted to run a loop forever, we can do as follows:

A line of code like this will allow us to run an infinite loop in our game because we are giving it a 1 second breather between each action.
Now, we don’t need to keep while loops in a coroutine at all times, but we have to be a lot more careful when we are creating them outside of a coroutine, as we do not have the yield method to work with. When outside of a coroutine, we have to always have an incrementor in place and a set end amount, otherwise we will again be stuck within an infinite loop and have to force close our program:

Now, lets take a look at an example using speed and max speed. What we will do is set up a speed and max speed variable and create a coroutine to work with:

As we can see, we created a short time delay between speed increases in our while loop and that if our speed goes higher than our max speed, it will only reach max speed and no further. From here, we can check on our editor to see if it works in the console:

--

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Recommended from Medium

Introduction to programming — tips for beginners

How I Knew (Becoming Trans In Eight Episodes)

Computer Shop Balerno

Balerno Computer Shop

How to activate search using Django and Django-filter

What I don’t like in your repo

Consolidated Casing Phase 4 Usps

Consolidated Casing Phase 4 Usps

WebHR Topped The Human Resources (HR) Category Leaders Q4 2017

Why Notion, But Why Not?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jordan Evans

Jordan Evans

More from Medium

Optimizing the Animator and Callouts

Creating ASCII Art!

Switch Statements | C#

Visual Studio: Regular expression to apply NameOf operator in C#— Coragi