loops in C# for Unity

Karuna Ketan
2 min readDec 7, 2022

--

I learned about loops in Unity…

7th Program:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour
{
[SerializeField] GameObject _item;

// Start is called before the first frame update
void Start()
{
int itemCount = 5;

// while Loop
while (itemCount > 0)
{
_spawnItem();
itemCount--;
}

// do-while Loop
do
{
_spawnItem();
itemCount--;
}
while (itemCount > 0);

// for Loop
for (int i = 5; i > 0; i--)
{
_spawnItem();
itemCount--;
}

}

// Update is called once per frame
void _spawnItem()
{
Instantiate(_item, new Vector2(Random.Range(6.5f, -6.5f), Random.Range(3.5f, -3.5f)), Quaternion.identity);
}
}

From above program:

There are 3 types of loops in C#:

1. while loop:

while (condition)
{
statements;
}

2. do-while loop:

        do
{
statements;
}
while (condition);

3. for loop:

for (statement 1; statement 2; statement 3)
{
statements;
}

That’s all…Thank you for Reading😅…

click here to follow me in LinkedIn for more updates…

click here to follow me in GitHub for more updates…

--

--

Karuna Ketan

Game Designer and Developer | Unity, Unreal Engine, Blender