Introducing Classes — Unity C#

We have seen how variables store information and how methods perform actions, but our programming toolkit is still somewhat limited. We need a way of creating a sort of super container that has its variables and methods that can be referenced from the container itself. Enter classes:

· Conceptually, a class holds related information, actions, and behaviors inside a single container. They can even communicate with each other.

· Technically, classes are data structures. They can contain variables, methods, and other programmatic information, all of which can be referenced when an object of the class is created.

· Practically, a class is a blueprint. It sets out the rules and regulations for any object (called an instance) created using the class blueprint.

A common Unity Class

Monobehaviour just means that this class can be attached to a GameObject in the Unity scene.

Classes are blueprints

This makes a post office a great example of a potential class that we can outline in the following block of pseudocode:

PostOffice
{
//Variables
Address = "1234 Letter Opener Dr."

//Methods
DeliverMail()
SendMail()
}

The main takeaway here is that when information and behaviors follow a predefined blueprint, complex actions and inter-class communication becomes possible.

For instance, if we had another class that wanted to send a letter through our PostOffice class, it wouldn’t have to wonder where to go to fire this action. It could simply call the SendMail method from the PostOffice class, as follows:

PostOffice.SendMail()

Alternatively, we could use it to look up the address of the Post Office so we know where to post the letters:

PostOffice.Address

Communication among classes

If we remember the post office example from earlier, the example code made use of periods (or dots) to reference classes, variables, and methods. If we think of classes as directories of information, then dot notation is the indexing tool:

PostOffice.Address

Any variables, methods, or other data types within a class can be accessed with dot notation. Dot notation is also what drives communication between classes. Whenever a class needs information about another class or wants to execute one of its methods, dot notation is used:

PostOffice.DeliverMail()

A VR/AR developer, who enjoys making games and developing interactive environments using Unity’s XR integration toolkit for Oculus quest and HTC vive devices.