Defining classes
Back in Chapter 2, The Building Blocks of Programming, we talked briefly about how classes are blueprints for objects and mentioned that they can be treated as custom variable types. We also learned that the LearningCurve
script is a class, but a special one that Unity can attach to objects in the scene. The main thing to remember with classes is that they are reference types—that is, when they are assigned or passed to another variable, the original object is referenced, not a new copy. We'll get into this after we discuss structs. However, before any of that, we need to understand the basics of creating classes.
For now, we're going to set aside how classes and scripts work in Unity and focus on how they are created and used in C#. Classes are created using the class
keyword, as follows:
accessModifier class UniqueName
{
Variables
Constructors
Methods
}
Any variables or methods declared inside a class belong to that class and are accessed...