Unity Shorts #1: Instantiating Game Objects

Let’s see how to spawn game objects in Unity, with 4 levels of difficulty!

This article is also available on Medium.

This tutorial is available either in video format or in text format – see below 🙂

When you work with the Unity game engine, one of the most fundamental concepts you’ll have to wrap your head around is the game object. Everything is based around them, from your on-screen characters to the sound effects, the UI and even the execution of your C# scripts.

Basically, a game object is an empty container that is filled with components to gradually compose a more complex behaviour. Some of those components are for rendering, others for physics collisions and gravity computation, others for emitting sounds, and of course you also usually want to drag and slap your own scripts on your game objects, to actually play your logic in the game!

So – game objects are essential, ok.

But how exactly do you create them? How do you spawn game objects in your Unity scenes, be it in edit mode or at runtime?

Today, we’re going to look at instantiating game objects into Unity with 4 levels of difficulty.

Ready? Let’s go then! 🙂

Level 1: Placing objects in edit mode

The first time you jump into the Unity editor, you might be a bit lost in all the UI, and the panels, and the assets visualisers, and the scene preview… But after watching a few YouTube tutorials and retaking the same steps over and over again, you’ll probably start to know your way around the software.

And chances are that, pretty soon, you’ll begin to populate your 3D scene with all kinds of objects: cubes, spheres, characters from the asset store, your own 3D models, and so on.

The process to add a new game object in your scene is amazingly simple:

  • if you want to create an empty anchor with no pre-defined component attached to it, or if you want to add very basic shapes like cubes and spheres for example, you can just go to the GameObject menu and take your pick.
    Those built-in basic meshes are called primitives and even if they probably won’t be enough if you plan on making your own AAA game, they’re usually a great starting point while the artists on your team are preparing the real assets.
  • if you want to instantiate one of your own project asset in the scene, then just drag it from your project folder into the scene view or the hierarchy

Using both those techniques, you’ll have a new object in your scene that you can select in your hierarchy and that has a position, a rotation and a scale – those are stored together as a Transform.

From there, you can add lots of components to boost your game objects and give them more advanced behaviours.

Level 2: Creating primitive shapes at runtime

Now, dragging stuff in your scene in edit mode is nice, but what if you want to spawn game objects at runtime? For example, what if you want to use procedural generation to get an infinite level for a runner game?

In that case, you obviously can’t prepare your game objects beforehand yourself! Instead, you’ll want to use a script to create your game objects.

If you’re still at the prototyping phase and you’re fine using primitives, then Unity actually makes it quite simple to create a new game object.

All you have to do is create a new C# script and import the UnityEngine package. Then, somewhere, call some code that uses the GameObject.CreatePrimitive() function. You’ll find all the primitive types you see in the editor ready to be used, and you’ll also be able to easily access the transform of the newly created object to set its position, rotation or scale.

Automating game objects instantiation is a really important skill for any Unity dev – but what if you’re passed the point where you’re using primitives? What if you want to copy back more complex game objects in your scene, with all the nice components you added earlier?

In that case, you’ll want to rely on “prefabricated objects”, or “prefabs”.

Level 3: Instantiating a prefab from a variable

Unity Prefabs are the key to creating re-usable assets. They allow you to store a game object in your project with all its current configuration, components and even hierarchy of child game objects so that this little piece of your scene is safely saved from one session to another… and can be reimported elsewhere in your game, either in edit mode or at runtime!

In edit mode, it’s just like before – you simply need to drag the prefab from your project folder and you’ll get a brand new copy of your game object.

Via script, however, it requires an additional step compared to primitive spawning. Since your prefabs are not Unity built-ins, the engine can’t just give you a direct reference to them by itself – rather, it’s up to you to get in your C# script a link to the prefab you want to instantiate.

A very common to do that is by simply declaring a game object variable in your script, either a public one or a private serialised one, so that it shows up in the Inspector.

Then, drag your prefab into the newly created slot that appears in your script-associated component.

Finally, inside the script, you can use Unity’s GameObject.Instantiate() method and use this reference to create new copy of your prefab inside the scene at runtime. Again, you’ll also have access to the position, rotation and scale.

However, this quick reference technique doesn’t work all the time…

What if the prefab to instantiate was created dynamically in a prior step? Or what if it depends on the context, and that the reference can only be computed when the script is executed? For example, what if you’re generating a dungeon map and you have dozens of wall variations, so that the player doesn’t see too much repetition; you’ll most likely won’t want to store all these prefabs inside your script, that would take a lot of space and make it hard to read!

Here, a better idea is to load the data directly from your project assets, at runtime.

Level 4: Loading up a prefab from your project assets

To be honest, Unity’s memory management and asset serialisation process is pretty complex; so there are lots of intricate details that you’ll have to get into if you really want your game to be optimised and fully cross-platform compatible…

But for prototypes or small-scale projects, a proven technique is to rely on the Resources folder, and the Resources.Load() method 😉

The Resources folder is a special folder that you can create in your project (it is not created by default) and that will be recognised by the Unity engine as “the place where you put addressable and dynamically loadable assets”. Everything that is put in this folder will be copied into the builds of your game which means that it will still be loadable at runtime in the built version.

Be careful, though, because overloading this folder with assets that do not require this setup can make for bloated builds

But anyway – if you do have some prefabs that you want to load dynamically at runtime, then simply put them inside the Resources folder (or any subfolder, for that matter, it will work no matter how deep the level!).

From that point on, you’ll be able to access the asset in your C# script with Resources.Load():

Don’t forget to specify the type of asset that you expect so that the compiler can safely retrieve it (for prefabs, you want to make a GameObject variable), and you’re all set to populate your scene with all kinds of neatly prepared prefabs!

Bonus: taking advantage of overrides!

By the way: in C#, just like in many other programming languages, you have this really neat feature of function overrides to let you call the same function in multiple ways. The idea is that you define several prototypes for the same method and so, depending on the parameters that you pass in, the engine will automatically look up the list of possibilities and use the matching logic.

Now, why am I talking about this?

Well because, in Unity, the GameObject.Instantiate() method actually has several prototypes, and in particular, it has one override for directly setting the position and the rotation of your object:

Sweet, right? We don’t need those extra lines anymore, we can just put everything in the Instantiate() call!

Conclusion

Game objects are literally at the core of the Unity game engine, at every stop of your game dev workflow, so knowing how to instantiate them both in edit mode and at runtime is a necessary skill for any Unity dev.

Today, we’ve looked at 4 techniques to spawn game objects in your scene either via the editor or using C# scripts.

I really hope you enjoyed the tutorial, please feel free to tell me if it’s been helpful in the comments! And of course, if you want to see more of this content, you can support my work by liking and sharing this content 🙂

Leave a Reply

Your email address will not be published.