We already discussed Game Objects and Components as two of the fundamental building blocks of the Unity Engine. Today, we’ll discuss their programmatic representation.
This is Unity for Software Engineers, a series for folks familiar with software development best practices seeking an accelerated introduction to Unity as an engine and editor.
The Unity Engine runtime is primarily written in C++, and much of the Engine’s primitives (such as the game objects and their components) live in C++ land. You’ll also know that the Unity Engine API is in C#. The API gives you access to all of Unity’s native objects in a way that — save for a few pitfalls we’ll discuss today — feels like intuitive, idiomatic C#.
At the top of the Unity Object hierarchy sits
UnityEngine.Object. For the most part provides a
name string, an
int GetInstanceID() method, and a bunch of equality comparers.
The class also provides a
static void Destroy(Object obj) method (and some overloads) that destroys a
UnityEngine.Object and any of its subclasses. When an Object is destroyed, the native part of the object is freed from memory, and the smaller managed part will be garbage collected at some point after there are no more references to it.
Because your valid reference to a
UnityEngine.Object can point to a destroyed native object,
UnityEngine.Object overrides C#‘s
operator!= to make a destroyed Object appear null. Simply accessing methods on a destroyed object will return
NullReferenceException, albeit with a friendlier error message that tells you which object you were trying to access.
A GameObject derives from Object and represents anything in your scene.
Let’s start at a high-level: A GameObject inherits a name and instance ID from its parent. Otherwise, conceptually, a GameObject