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:
GameObject gameObject = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath("Assets/MainCamera.prefab", typeof(GameObject)));
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):
public class SomeScript : MonoBehaviour {
public GameObject prefab;
}
Or by putting the prefab in the Resource folder and using Resources.Load
:
GameObject prefab = Resources.Load("Assets/Resources/MainCamera");
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):
GameObject gameObject = Instantiate<GameObject>(prefab, new Vector3(0,0,0), Quaternion.identity);
Note: Prefab term does not exist at runtime.