Methods

Overview

In this lesson we focus on methods. One of the most powerful ways to extend and organize our code.

The Code

Let’s first look at the Random class we use in this lesson.

class Program {

	static void Main(string[] args) {
		Random rnd = new Random();
	}
	
}
  • Line 4 – The Random Class is very important in game development. It is often utilized to create all random elements in games and even helps aid in simple enemy AIs. You can explore the Random class more by clicking here.
class Program {

	static void Main(string[] args) {
		// ...
		static void AskQuestion() {
		
		}
	}
	
}
  • Line 5 – This line contains the header of the method we are constructing. You will noticed there is some key words here.
    • static – The static keyword in C# means that there can only be one instance of the method. This may be confusing right now because you are not dealing with multiple objects. Still, think about this, you have two enemies with the same C# script attached to them for their AI. Normal methods, that do not use the static keyword would get their own copy of the method that would function independently from the other enemy. Yet, if you add the keyword static, they would “share” that method, this means when you invoke the method you would invoke it on both enemies.
    • void – The void keyword can change depending on the type of variable you want to return. In this cases we are not returning anything so we use the keyword void. But, if we wanted to return an int variable the keyword would change from void -> int.
    • AskQuestion() – The AskQuestion part is the name you give the method, notice how it starts with a capital and each new word is capitalized. The () is needed, it is where you would pass parameters (data or information) into to share information among different methods and classes.

Deliverable

The deliverable for this lesson is your finished product from this lesson. Unlike other lessons so far you do not have to do any extra work or code.

Assignments in this module are handed in via Google Classroom. Make sure you are signed into your PLSD account and click the link below:

Mark as Complete
chevron_right