Prefabs are an editor only feature. That's why the PrefabUtility is an editor class. Prefabs are just serialized standalone assets. At runtime you can only use assets which you have created in the editor. Utility class for any Prefab related operations. // Create a folder (right click in the Assets directory, click Create New Folder) // and name it “ Editor ” if one doesn’t exist already. Place this script in that folder. // This script creates a new menu item Examples Create Prefab in the main menu.
There are 2 ways of instantiating prefabs: during design time or runtime.
Instantiating prefabs at design time is useful to visually place multiple instances of the same object (e.g. placing trees when designing a level of your game).
To visually instantiate a prefab drag it from the project view to scene hierarchy.
If you are writing an editor extension, you can also instantiate a prefab programmatically calling PrefabUtility.InstantiatePrefab()
method:
Instantiating prefabs at runtime is useful to create instances of an object according to some logic (e.g. spawning an enemy every 5 seconds).
To instantiate a prefab you need a reference to the prefab object. This can be done by having a public GameObject
field in your MonoBehaviour
script (and setting its value using the inspector in the Unity Editor):
Or by putting the prefab in the Resource folder and using Resources.Load
:
Once you have a reference to the prefab object you can instantiate it using the Instantiate
function anywhere in your code (e.g. inside a loop to create multiple objects):
Note: Prefab term does not exist at runtime.
Author: Matthew Miner (matthew@matthewminer.com)
Creates a prefab containing the contents of the currently selected game object.
Place the script inside the Editor folder. Select a GameObject and choose 'GameObject > Create Prefab From Selection'. A new prefab will be created in the root directory bearing the same name as the GameObject.
Faults:
I decided to update this script in can anybody is intewrested. It now will give a popup if the prefab already exits and you can choose to overwrite the prefab or cancel. It also replaces the selected gameObject with the new prefab.
- Updated to accept multiple selected objects and not use /prefabs folder (without it it deletes the GO without creating prefab)
- Fixed the script to make sure the new object have the same parent as the old one in the scene. --Blikstad 06:11, 20 May 2012 (PDT)
- Extended with choice of save folder by winxalex
Small update for procedural mesh creations: it saves the created mesh to disk and inside a prefab, instead of losing it, and keeps all prefab size, shader, collider, and script settings in 1 prefab.
Requires that you have a folder called Assets/savedMesh