Instantiate Unity Objects Like a Pro(grammer) Part I

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 I covers creating a prefab, if you’re looking for code or only want to instantiate empty game objects – check out Part II here.

 

Example object of a chair.
The chair is not against the wall.

Step 1: Create a Thing

Create the object you want to make a prefab of in the scene. It can be as simple as a cube or as complex as the USS Enterprise – it makes no difference. If you’re painfully unartistic like myself, Unity provides a resource store with thousands of assets to make your life easier. Get started by checking out our guide here.

 

Make a Prefabs folder.
Make a Prefabs folder.

Step 2: Create a Folder

If you don’t have a dedicated folder for your prefabs already, make one now. In your project window, click on your Assets folder. In the sub-window (Assets) right click anywhere in the space and click Create -> Folder. Name it ‘Prefabs’ or any other such name so that you’ll remember that this is where you prefabs live.

 

Drag the object into the Prefabs folder.
Drag the object into the Prefabs folder.

Step 3: Drag the Thing into the Folder

Pretty self-explanatory. Drag the game object you created into your Prefabs folder. Admire the pretty blue color that that the object name turns into in the hierarchy window afterward – this means it’s a prefab clone. Congrats! You’ve made a prefab. Gold star.

 

Object is in Prefabs folder.
See? Still there.

Step 4: Delete the Thing

Swallow that cold, hard lump of fear in your throat and delete the object out of your hierarchy window. It’s cool, you’ve got it saved for life. From your Prefabs folder you’ll be able to drag-and-drop the object back into your hierarchy window for a perfect clone every time. Tip: If you edit one of your prefab clones (indicated by the blue color) and want to apply the changes to your original object. make sure to hit ‘Apply’ in the inspector window.

Apply to save changes to the original object.
Apply to save changes to the original object.

 

What kinds of prefabs are you working on? Tell us about them in the comments below!

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

Leave a Reply

Your email address will not be published. Required fields are marked *