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