How to Use Instantiate in Unity: Simple Object Creation
In Unity, use
Instantiate to create a copy of a GameObject or prefab at runtime. It requires the original object and optionally a position and rotation to place the new object in the scene. This lets you spawn objects like enemies, bullets, or effects dynamically.Syntax
The basic syntax of Instantiate is:
Instantiate(original): Creates a copy of the original object at the same position and rotation.Instantiate(original, position, rotation): Creates a copy at a specific position and rotation.originalis the object to copy, usually a prefab or existing GameObject.positionis aVector3specifying where to place the new object.rotationis aQuaternionspecifying the new object's rotation.
csharp
GameObject newObject = Instantiate(original, position, rotation);
Example
This example shows how to spawn a prefab at the origin with no rotation when the game starts.
csharp
using UnityEngine; public class SpawnExample : MonoBehaviour { public GameObject prefab; void Start() { Vector3 spawnPosition = Vector3.zero; Quaternion spawnRotation = Quaternion.identity; GameObject newObject = Instantiate(prefab, spawnPosition, spawnRotation); newObject.name = "SpawnedObject"; } }
Output
A new instance of the prefab appears at position (0, 0, 0) with no rotation, named "SpawnedObject" in the scene.
Common Pitfalls
Common mistakes when using Instantiate include:
- Forgetting to assign the prefab in the inspector, causing
nullerrors. - Not setting the position and rotation, which may place the object unexpectedly.
- Assuming
Instantiatemodifies the original object instead of creating a copy. - Not storing the returned object reference if you want to modify or track the new instance.
csharp
/* Wrong: Not assigning prefab in inspector */ public GameObject prefab; void Start() { Instantiate(prefab); // prefab is null, causes error } /* Right: Assign prefab and store reference */ public GameObject prefab; void Start() { if(prefab != null) { GameObject clone = Instantiate(prefab, Vector3.zero, Quaternion.identity); clone.name = "Clone"; } }
Quick Reference
Remember these tips when using Instantiate:
- Always assign the original object (prefab or GameObject) before calling
Instantiate. - Use
Vector3andQuaternionto control spawn position and rotation. - Store the returned object if you need to change or track it.
- Use
Destroyto remove instantiated objects when no longer needed.
Key Takeaways
Use Instantiate to create copies of GameObjects or prefabs at runtime in Unity.
Always provide the original object and optionally position and rotation for precise placement.
Assign prefabs in the inspector to avoid null reference errors.
Store the returned object from Instantiate to modify or manage the new instance.
Remember to destroy instantiated objects when they are no longer needed to free resources.