Unity lets you make games of any kind for any platform. It’s revolutionary but its flexibility can lead to a system which is hard to understand. Here’s what I learnt making my game as a handy reference.
Cheatsheet
Which building blocks do I use and when?
GameObject | ScriptableObject | MonoBehaviour | No inheritance | |
---|---|---|---|---|
What | The entities that interact with each other. | Data models editable via Unity UI. |
GameObject actions and data flow. | Basic C# class. |
When | If it can be seen in the game world. | To define the settings of GameObject s and general configuration. | To control GameObject s, generate and handle events. | When behaviour not directly related to a GameObject . |
Where | Lives in the Hierarchy. | Lives in the ProjectView. Initialized by Unity. | Attached to GameObject s as a Component, or lives in the Hierarchy. | Lives in the ProjectView. Called programatically by other scripts. |
Example | Scene.unity | Config : ScriptableObject | PlayerController : MonoBehaviour | SaveController |
Use Cases |
|
|
|
|
Accessors
In Unity most things are GameObject
s which scripts are attached to. In your scripts you can access most things with these 3 snippets:
- Get the instance of the script/class we’re in with
this
. - Get the GameObject the script is attached to with
this.gameObject
. - Get the GameObject’s components with
GetComponent<ComponentName>()
.
The longer versionthis.gameObject.GetComponent<ComponentName>()
will also work.
If you’re searching for GameObjects in the Scene Hierarchy:
- Find a GameObject by name:
GameObject.Find("name")
- Find a GameObject of a certain type:
GameObject.FindObjectsOfType(typeof(MyType));
- Find a GameObject with a certain tag:
GameObject.FindGameObjectsWithTag("MyTag");
Debugging
Using breakpoints via Visual Studio is the best way to debug complex data flows, but sometimes you just want good old fashioned debugging.
List components and all their variables
Put using System.Reflection;
at top of file then paste:
Shortcuts
You will need to keep running the main scene and navigating to it in Unity then running it is tedious. Create a keyboard shortcut instead with:
Replace <scene-name>
with the name of your scene. Now M
key on your keyboard will run the main scene from anywhere.