Day 9: Instantiating & Destroying Gameobjects in Unity
Objective: Spawn an object and destroy it when it’s off the screen.
When we spawn an object we will use an system called instantiate. To use this we will need a game object that is a prefab. To start create a 3D object and move to project folder to make a prefab. In the project area, the name will turn blue to signify it’s a prefab.
Now the code, first thing to do is get a reference to the prefab.
Now to check for input to instantiate the object and then instantiate the object.
In the Instantiate, you need to pass in some data. The first will be the object to be created. The next is where it will be instantiated, so we use the player’s position(since this script is on the player). Lastly, we need the rotation, here we use the object’s original rotation.
Next will be to assign an object to the GameObject reference. Back in Unity, take the prefab you created, from the project window, and add to the player component on the Player object. Do not take a prefab from the hierarchy, because once it spawns the first time the object will disappear from the reference.
That will spawn the object, Now to delete the object.
We will need to create another script called Laser, for the laser’s behavior.
In that script we will need a reference for speed and use transform.Translate() to move the object up.
Now to destroy the object after it gets to high. We will check the y position of the object and if it’s greater than a specified position we will destroy.
That’s it! We have spawned an object into the game and forced it to move up until a certain position and then it gets destroyed.