Instantiating & Destroying Game Objects in Unity
To spawn a game object into your game world using Unity without having the game object cluttering your hierarchy you need to create a prefab and instantiate it. Create a prefab by:
- right clicking in the project window and create a prefabs folder in the assets folder.
- Now right click in the hierarchy and create your game object and drag it to the prefab folder to create your prefab.
- Now delete the game object in the hierarchy.
Now to spawn the game object in your game use instantiate() using a C# script. To do this add a cube to your scene and create a script on the cube. In the script:
- Reference your game object
- Instantiate it using instantiate(gameObject, position, rotation)
- now save that and go to unity and add the prefab to the script and when you play the scene the prehab will instantiate
Now to destroy the cube so you can see the prefab use Destroy()
- Open the script and use Destroy(this.gameObject) to destroy the cube
- This should be done after you instantiate the game object
Now you have successfully used instantiate() and destroy().