Introduction to the Object-Oriented Paradigm
Before we get started with Unity, it’s important that we go over the basics a little. Unity supports both C# and Javas- cript for game programming; we’ll be working with C# for this tutorial. First off, if you’ve never programmed before, put this tutorial aside and spend a few days working through Microsoft’s C# Language Primer until you feel comfortable using the language for simple tasks. If you have programmed before in an imperative or object oriented language like C or Java, skim the primer and familiarize yourself with how C# differs from other languages you’ve used in the past. Either way, don’t proceed with the tutorial until you feel comfortable solving simple problems with C# (for example, if I were to ask you to write a program that prints the first hundred prime numbers, you should be able to write that pro- gram without consulting Google).
The most important concept to understand here is the object-oriented paradigm (abbreviated as OOP). In object ori- ented languages, programs are divided into functional units called Objects. Each object has its own private variables and functions. Object-specific functions are called methods. The idea here is modularity: by having each object iso- lated, and forcing other objects to interact with it through its methods, you can reduce the number of possible uninten- tional interactions - and, by extension, bugs. You also create objects you can reuse at will later with no modification. In Unity, you’ll be building these objects and attaching them to game entities (whose behavior they’ll govern).
Objects are instantiated from classes: a class is just a file that lays out the definition of your object. So, if you want a‘Mook’ object that handles AI for an enemy in your game, you’d write a ‘Mook’ class, and then attach that file to every enemy entity. When you run your game, each enemy will be equipped with a copy of the ‘Mook’ object.
Attaching a new script to an object looks like this:
First, select the object and go to the inspector. Then, click on the ‘Add Component’ button.