Bite Sized Tech is a participant in Unity Affiliate Program, Liquid Web Affiliate Program, Hostinger Affiliate Program, Namecheap Affiliate Program, Envato Elements Affiliate Program, Adobe Affiliate Program and SteelSeries Affiliate Program under which we might earn commission when visitors use our Affiliate Links and makes qualifying purchases.


Do While Loop | Unity C# Game Development Tutorial | How To Make A Game


Do While Loop just like all the other loops is used to loop through the elements of an Array, Dictionary, List or Collection.

In the previous articles we have gone through the For Loop, Foreach Loop and While Loop already,

In today’s article, we will go through the last kind of loop i.e. Do While Loop

and learn everything about it using an RPG Analogy of your Player being a Pirate and is being chased by Marines.

So, without further ado, let’s get started!


This Post is Part of : How To Make A Game Series where I’ll be showing you how to become a game developer and will be going over the basics of Game Development, Step by Step, using the Unity Game Engine and C# Scripting Language to script the Game Logic.

If you are new to Game Development or Programming in general you should definitely go through this Unity Tutorials article series as it will set give you a kick-start towards becoming an exceptional Unity 2D or 3D Video Game Developer.

It is really easy to lose focus of what is really important, when you get in the zone while Designing and Developing your games.

This can be problematic because this can lead you to spending a ton of your time on some Game Mechanic or Game Art

only to realize it does not add much to your overall Game.

Thus, completely wasting your extremely precious and valuable time.

This can be really painful and to stop that from happening to you, I’ve written this article on 3 Points To Focus On When Designing A Game

in which I’ve highlighted 3 Points that you should always keep in your head while making Game Design and Game Development Decisions.


While Loop - Unity C# Game Development Tutorial - How To Make A Game - Featured Image

List Of Other Articles on Loops In C#



Syntax Of Do While Loop in C# | Unity Game Development Tutorial

In the last article, we talked about While Loops and building on that

we are going to talk about Do While loop in this article.

Now, because the While loop and Do While loop are so similar,

lets directly go over the Syntax of the Do While Loop.

// Everything below is inside a Class.
// The code below is just to understand the Syntax.
// For working example move further down in the Article.

void Start()
{

  in i = 0;

  do
  {
    // Code Block
    i++; // Increment or Decrement Step
  }
  while(condition) // Something like i < 10

}

The Do While loop starts with the do Keyword

followed by the code block

and After that, we have the While Keyword and the two Opening and Closing Parenthesis

with a condition of the While Loop inside the parenthesis.

Just like the While Loop,

Initialization of the control variable of the Do While Loop, is done before the loop itself

and the Increment or Decrement step is done inside the code block.

If the condition for the While Loop, evaluates to true,

then the code block will be executed again

and if the condition returns false

then the program will Stop the While Loop’s execution

and exit the While Loop.

The Do While Loop is the same as the while loop in everything

except that, it executes the code block at least once

before the condition for the While Loop is checked for the first time.

This is because, the condition is specified at the end of the block

rather than at the start of the block

like we have seen in other loops like For Loop, Foreach Loop and While Loop

Just something to keep in mind, when coding a do while loop is that

because the increment or decrement step is done inside the code block

it will be performed once

even before the condition for the do while loop is checked for the first time.


Do While Loop RPG Analogy | Unity Game Development Tutorial

Now, lets move on to the RPG analogy

and think about a scenario where the Player is controlling his Pirate Ship

and is trying to escape the Marine ships which are chasing and attacking him.

So, what we need to do now is use do while loop to recreate this scenario

where the enemy ships will shoot cannon balls at the player’s ship

and at random will hit or miss the ship.

We will also be keeping a log of

how many cannon balls hit the player’s ship

and how many missed the ship and fell into the ocean.

If we hit the player, we will also debug.log the change in the player’s HP

and when player’s HP turns 0,

we will stop attacking the player and log the battle stats.

That’s it.

So, let’s dive into the code and get this done.


Do While Loop Code Example | Unity Game Development Tutorial

Declaring And Initializing Necessary Variables & Your First While Loop

First of all, we will declare a boolean

named _continueToAttack and set it to true

Then declare an int

named _cannonBallsHit and set it to 0

After that declare another int

named _cannonBallsMissed and set it to 0

Next we will declare one more int

named _playerHP and set it to 100

With that done, Now in the Start() Method

We will create a do while loop with condition being

_continueToAttack == true

like this

// Everything below is inside a Class.

private bool _continueToAttack = true;
private int _cannonBallsHit = 0;
private int _cannonBallsMissed = 0;
private int _playerHP = 100;

void Start()
{

  do
  {

  }
  while(_continueToAttack == true);

}

Writing Code For Cannon balls Randomly Hitting Or Missing The Player’s Ship

Next, inside the code block

we will declare an integer named randomHit

and set it to a random number between 0 and 2

which means that it’s value will either be 0 or 1

After that we will create an if statement with the condition being

randomHit == 0

which will mean that, the cannon ball did not hit the player’s ship

So, inside if’s code block,

we will first increase _cannonBallsMissed by 1

and then Debug.Log

“Where are you aiming at sailor?!”

like this.

// Everything below is inside a Class.

private bool _continueToAttack = true;
private int _cannonBallsHit = 0;
private int _cannonBallsMissed = 0;
private int _playerHP = 100;

void Start()
{

  do
  {

    int randomHit = Random.Range(0, 2);

    if(randomHit == 0)
    {
      _cannonBallsMissed = _cannonBallsMissed + 1;
      Debug.Log("Where are you aiming at sailor?!");
    }

  }
  while(_continueToAttack == true);

}

With that done, after the if block

we will create an else if block, with the condition

randomHit == 1

Which will mean that, the cannon ball hit the player’s ship and inflicted damage

So, inside the curly braces of the this else if block

we will first increase _cannonBallsHit by 1

After that, we will reduce player’s HP by 10

and then Debug.Log

“Nice aim sailor! Destroy that little ship!!!”

and also Debug.Log the player’s recalculated HP,

like this

// Everything below is inside a Class.

private bool _continueToAttack = true;
private int _cannonBallsHit = 0;
private int _cannonBallsMissed = 0;
private int _playerHP = 100;

void Start()
{

  do
  {

    int randomHit = Random.Range(0, 2);

    if(randomHit == 0)
    {
      _cannonBallsMissed = _cannonBallsMissed + 1;
      Debug.Log("Where are you aiming at sailor?!");
    }
    else if(randomHit == 1)
    {
      _cannonBallsHit = _cannonBallsHit + 1;
      _playerHP = _playerHP - 10;
      Debug.Log("Nice aim sailor! Destroy that little ship!!!");
      Debug.Log("HP : " + _playerHP);
    }

  }
  while(_continueToAttack == true);

}

With that done outside the curly braces of the else if block,

we will create another if statement

but this time with the condition being

_playerHP == 0

If this evaluates to true, then it means that

the player’s ship has been destroyed and the player has drowned

So, inside this if’s curly braces, first of all

set _continueToAttack to false

which will stop the Do While Loop,

when the program checks the Do While Loop’s Condition the next time.

After that Debug.Log

“Nice work sailor! That will teach these outlaws a lesson!”

And then Debug.Log the Battle Stats

about how many cannon balls Missed and Hit the player’s ship

like this

// Everything below is inside a Class.

private bool _continueToAttack = true;
private int _cannonBallsHit = 0;
private int _cannonBallsMissed = 0;
private int _playerHP = 100;

void Start()
{

  do
  {

    int randomHit = Random.Range(0, 2);

    if(randomHit == 0)
    {
      _cannonBallsMissed = _cannonBallsMissed + 1;
      Debug.Log("Where are you aiming at sailor?!");
    }
    else if(randomHit == 1)
    {
      _cannonBallsHit = _cannonBallsHit + 1;
      _playerHP = _playerHP - 10;
      Debug.Log("Nice aim sailor! Destroy that little ship!!!");
      Debug.Log("HP : " + _playerHP);
    }

    if()
    {
      _continueToAttack = false;
      Debug.Log("Nice work sailor! That will teach these outlaws a lesson!");
      Debug.Log("Cannon Balls Missed : " + _cannonBallsMissed);
      Debug.Log("Cannon Balls Hit : " + _cannonBallsHit);
    }

  }
  while(_continueToAttack == true);

}

and with that the code is complete.

Now let’s execute this piece of code in Unity and check the logs.



Unity Log | Do While Loop Code Example | Unity Game Development Tutorial

Do While Loop Code Example - Unity Log 1 - Unity C# Game Development Tutorial
Do While Loop Code Example - Unity Log 2 - Unity C# Game Development Tutorial

As you can see, throughout the logs

we are randomly hitting and missing the player’s ship

and when the player’s hp turns 0,

we are correctly logging the Battle Stats

i.e. how many cannon balls hit the player’s ship and how many fell into the ocean.


Some Important Points About Do While Loop Before Wrapping This Article Up

Now same as the other loops

we can create a Nested Do While Loop

by encapsulating a Do While Loop into another Do While Loop.

and as in the article about While Loop

i’m not going to cover it in this article

as i have already shown it pretty extensively,

in the articles about For Loops and Foreach Loops

and there is nothing new to show about it.

With that done, we have covered all the Loops in C#.

And we can finally move on to a very important topic in the next article

which is Methods or as some of might call it Functions.


Conclusion

Well folks, that does it for this article.

i hope that this information will be helpful to you.

Share this post and follow us on Social Media platforms if you think our content is great, so that you never lose the source of something you love.

If you like the content do go through the various articles in How To Make A Game Series that this post is a part of and also go through the other series we have on Bite Sized Tech.

Also we have a YouTube Channel : Bite Sized Tech where we upload Informational Videos and Tutorials like this regularly. So, if you are interested do subscribe and go through our Uploads and Playlists.


Follow Us On Social Media


Goodbye for now,
This is your host VP
Signing off.