Class
How to use Classes when making your game.
A Class is a group of related Variables and Functions. It allows your game to know what something is and what it can do.
Summary
A Class is a group of related Variables and Functions, known as Members. It allows your game to know what something is and what it can do.
- Variable
- Holds data of a certain Type (text, number, true/false, other class, etc)
- Examples: Age, Color, Weight
- Function
- Executes an action. Makes something happen.
- Examples: Jump(), Move()
Just like high school, mathematics class contains all the information about mathematics. Mathematics doesn’t contain any information about history or art.
A Class can be added to a GameObject as a Component.
An Object (or Instance) is a version/copy of a Class that exists “in the world” (in memory). Think of a Class as the recipe, and the Object/Instance as the cake. Many Instances can be created from the same Class.
Variable Basics
Variables can hold different types of data.
Standard Types
int number; // Holds a single whole number
float decimalNum; // Holds a single decimal number
string text; // Holds text
bool trueOrFalse; // Holds a true or false value
Unity Types
GameObject go; // Holds a GameObject
Transform t; // Holds a GameObject's Transform component
Vector2 twoNumbers; // Holds two numbers (x, y)
Vector3 threeNumbers; // Holds three numbers (x, y, z)
Others
GameObject[] array; // Holds many GameObjects
List<Transform> list; // Holds many Transform components
Dictionary<string, GameObject> dictionary; // Holds many GameObjects found using a string ID
CustomClass myClass; // Holds a custom class
Access
Variables can be public or private (and more).
- Public means it is accessible from other Classes.
- Private means it is only accessible from inside its own Class.
Function Basics
Functions make something happen when executed. They are sometimes called Methods.
Standard
void Jump()
{
Debug.Log("Jumped");
}
With a Parameter
void Jump(int howHigh)
{
Debug.Log("Jumped " + howHigh + " metres into the air");
}
Returns a Type
bool IsAlive()
{
if (_currentHealth > 0)
{
return true;
}
else
{
return false;
}
}
// Can be used like so:
void TestFunction()
{
if (IsAlive())
{
// Alive
}
else
{
// Dead
}
}
Examples
- http://pastebin.com/cnSUVVac
Class vs Unity Component
- Instantiating is different for both
- Class -
ClassName varName = new ClassName();
- Component -
ClassName varName = gameObject.AddComponent<ClassName>();
, or click-drag the component onto the GameObject.
- Class -
Notes
- Classes should be a group of related things. In school, a history class does not teach mathematics. They focus on one topic.
- https://forum.unity.com/threads/component-based-weapon-system.204999/
- Self - Make differences between classes/structs clear
- http://www.tutorialsteacher.com/csharp/csharp-class
- http://www.tutorialsteacher.com/csharp/csharp-data-types
- C# Programming Yellow Book by Rob Miles