Want to instantiate empty game objects or prefabs programmatically but are not quite sure how to do it? Look no further! We’ve created step-by-step instructions on how to create game objects and instantiate them at run time so you can sit back and relax like the pro you are.

Part II covers creating and implementing instantiation scripts, if you’re looking for how to create prefabs – check out Part I here.



Create a script file.

Create a script file.

Step 4: Create a Script

Create a new folder in your Assets called ‘Scripts.’ Open the folder, right click anywhere in the sub-window and choose Create -> C# Script. Name it whatever you wish, then double click it to open the script in the editor of your choosing.



Example of code.

R.I.P. MonoDevelop

Step 5: Code Some Stuff

Instantiating objects can be done by calling Instantiate() or, for empty objects, declaring a new GameObject(). Overloads and specifics for Instantiate() can be found here. After instantiation, you can add components such as rigid bodies, meshes, colliders, or whatever your little heart desires. I’ve added a box collider to both types of instantiated objects as an example below.



Step 6: Save Your Work

Jim Carrey typing furiously.

Bonus points: Hit Ctrl/Cmd+S multiple times in rapid succession like a madman.


Step 7: Prepare For Magic

To see your script in action, you can call it from another script or you can assign it to something that you know will load it anyway. For this example, we’re going with the latter. Back in Unity, in your hierarchy window, create an empty game object in the scene. This is what will call our script. Next, drag your script onto the inspector window of your empty game object so that it adds as a component.


Instantiating Prefabs
Script added as a component.

See the little selector for your desired prefab? Add it now.

Prefab is added.

All set.

Instantiating Empty Game Objects
Script added.

Do nothing. You’re golden.



Man with feet on his desk.

Relax. You’ve earned it.

Step 8: Experience Magic

Hit play and sit back to watch as all of your hard work pays off.

Before/After runtime with prefab.









Before/after runtime with prefab.




Before/after runtime with empty game object.

Before/after runtime with empty game object.


Note: Unity likes to change syntax in their updates for no particular reason. This post currently covers version 2017.2.1.

Questions? Comments? Post them below!

Like this post? Share it!