Class = component
Still reading. The Player.cs shape here is the shape of every script you write from lesson 06 on.
Start with one word: GameObject. Everything that exists in your game — the floor, the camera, a character, a bullet — is a GameObject.
On its own a GameObject is an empty doll. It has a name and a place to stand, and nothing else: you cannot see it, you cannot touch it, it does nothing.
You make it real by clipping parts onto it. Each part is called a component. And the C# class you are about to write is simply one more part you clip on.
Watch the four parts clip on one by one — only after the last one does the character actually move.
The four parts, in plain words
Transform — where it stands, which way it faces, how big it is. Every GameObject has this one and it can never be removed.
Mesh Renderer — the part that actually draws it on screen. Take this off and the character is still there, just invisible.
Collider — an invisible body. Without it the character walks straight through walls and the floor.
Player.cs — the part you write yourself. It is what decides: when the player presses W, walk forward.
Now write the fourth part yourself
Unity wrote the first three parts for you. The fourth one — the brain — is a C# file. Every Unity script has the same shape, and you only ever change what is inside the braces.
using UnityEngine; // gives you Vector3, Debug, ...
public class Player : MonoBehaviour // ": MonoBehaviour" = attachable component
{
public float speed = 5f; // shows in the Inspector
[SerializeField] private int hp = 100;
private bool isDead; // pure code, no Inspector
void Start()
{
Debug.Log(name + " ready, hp = " + hp);
}
}The line ": MonoBehaviour" is the whole trick. It is what turns an ordinary C# class into a part you are allowed to clip onto a GameObject. Leave it out and the script cannot be attached to anything.
The file must be called Player.cs — Unity matches file name to class name or the component will not attach.
public = other scripts can read it AND it appears in the Inspector.
[SerializeField] private = the best default: visible in the Inspector, invisible to other scripts.
A field is declared once in code; after that you tune it in the Inspector while the game is running.
Create and attach a script
- 1
In the Project window: (older Unity: C# Script).
- 2
Type the name immediately — renaming later does not rename the class inside.
- 3
Select a GameObject in the Hierarchy, then drag the script onto the Inspector.
- 4
Press Play. Anything you Debug.Log appears in the Console window.
Reaching other components
private Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>(); // on this same object
}