Unity C# — Methods|Functions

Joshua Villarreal
2 min readJul 3, 2022

--

Example of methods|functionsf ref:Microsoft

Methods (or Functions as some would call them) are what take the variables we have and will manipulate them to do various tasks.

In a previous article, Classes were mentioned to be containers of various data such as variables and methods. These classes are in scripts and attached to game objects within unity.

With methods we can make the attached game object act in a way that we want: From creating game managers that can handle spawning of enemies, to the player character, or handling menu options.

In this example, we have a method to spawn enemies inside of a spawn manager

In this Coroutine Method, we use a while loop (we’ll cover loops in a later article) to spawn an enemy using the Instantiate Method (this is a built in method that Unity provides us with to create objects with code). We then wait a certain amount of time before we check the loop condition to see if we will spawn another enemy.

Heres a set of code from the player that contributes to the spawning code

in this method within the player, the amount of lives get decreased by one and then if they are 0 or lower we then tell the spawning manager to stop spawning enemies.

Its just that easy to write methods that can communicate with other methods. These methods must be public methods though. if a method doesn’t have an access type or is private then they can only be used by the script they are within.

We have to talk about Coroutines now that they have been brought up.

Coroutines are like normal functions, However, They can be called|invoked repeatedly and with varying amounts of wait time between each call.

Couroutines return and IEnumerator type.

With IEnumerators, we can tell a Coroutine to wait a single frame or a set amount of seconds as an example.

Next time, I’ll go over loops and then we can start diving into game dev!

--

--

Joshua Villarreal
0 Followers

Professional Unity Game Developer creating articles to journal Unity/C#/Git features from Beginner to Pro