Understanding Unity Engine Objects

Eyas
7 min readJul 20, 2022
Photo of metallic structures forming a frame of a building.

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#.

A GameObject, MonoBehaviour, and ScriptableObject all inherit from UnityEngine Object
The C# class hierarchy of UnityEngine.Object, GameObject, ScriptableObject, Component, and their children. This should map to the conceptual hierarchy of how to think about these objects, though sometimes the runtime implementation will look different.

UnityEngine.Object

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== and 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.

GameObject

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

  • has a list of Components on it,
  • has a tag string for organizational purposes, and
  • belongs to a layer.

--

--

Eyas

Software Engineer living in Brooklyn, NY. MIT Computer Science S.B. ’13, M.Eng. ‘14. From Amman, Jordan. Interested in politics, current affairs, and technology