Instantiating & Destroying Gameobjects in Unity
A “transform” is a “gameObject.”
“Instantiate” creates a clone of a Prefab original transform. This means the Instantiate() function returns a reference to a new clone.
“Spawn” means “Instantiate.”
The sequence of steps to instantiate include the artwork to put an object into the game, the modification to make the object cloneable, the addition of instantiation code to another object’s code, the connection with a matching script, and the coding inside the script to detail the action of each clone.
Here details to show the step by step of launching a capsule named Lazer from another primitive cube named Player.
First <right-click> to create a new capsule gameObject.
Unity’s creation parameters are standardized, so adjust the size as needed. Here is a scale of 0.2 and a position Vector3 of 0,0,0.
In Unity, an object created at run-time gameplay is a formed from a prefab object. Create a new folder to contain the prefab list of assets.
<drag> the Lazer object into the Prefab list folder
Components of the Prefab can be added in the same <right-click> and create as before the object was dragged to the folder. Remember the naming convention of _mat, so Lazer_mat.
Here is the addition of a Blue color to the Object’s Albedo material. <drag> and drop the Lazer_mat from the Assets up to the Hierarchy Game Lazer to link the material with the object.
This important step allows Unity to clone the Prefab Laser components. <click> on the Laser in the Hierarchy, “Lazer” appears in the Prefab field, and <click> Apply All in the Overrides dropdown.
With the artwork taken care of, the next step will need to reference documentation to learn the coding behind the desired effect on the gameObject. When googling a howto, always add Unity to the end of the search keywords.
In this example, we want to have the capsule appear and move up the y-axis. Instantiate is also referred to as spawning, which is useful in documentation searching.
The Lazer comes from the Player. First test the code to create a Laser from a Player.
Here is the Visual Studio view for the Player cube. A press of the space-bar instantiates a Laser capsule.
Looking at keyboard access, there are choices: press, up, down. Then there is a keycode.
// Update is called once per frame
void Update()
{
CalculateMovement();
// if I press spacebar
// instantiate clone object
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Spacebar pressed down\n");
}
}
The console message can be found at the bottom left of the Unity environment.
Also, a console view can be created by <right-click> the bottom row message. Now <click> and drag the “Console” of the view’s corner up to be a new tab next to the Game tab.
There is a three-dot icon to the right corner of the view available to make fine adjustments, including a delete of the tab.
Input <spacebar> is operational, now to instantiate an object.
The Player object receives a keyPress. the Player object instantiates a Laser object. Start with a public object, declared outside of the Start or Update methods. The object will be a serialized private object later on soon.
public class Player : MonoBehaviour
{
public GameObject laserPrefab;
// Start is called before the first frame update
void Start()
{
}
If the laserPrefab is public, then after a Unity compile, delete the laser from the Hierarchy list, if there is one, and…
<click> to highlight the Hierarchy Player object (this displays the Inspector view of the Player object
drag the Laser object in the Project view Prefabs folder across to the Laser Prefab field in the Player’s Inspector view.
before the drag:
After the drag:
This is drag and drop is while the laserPrefab is a public gameObject. Easy because of allowable use of the Inspector view with one Prefab object.
The Problem with a private gameObject (note the underscore character):
public class Player : MonoBehaviour
{
private GameObject _laserPrefab;
// Start is called before the first frame update
void Start()
{
}
The Prefab laser disappears from the Inspector view:
Add [serializeField] and note the underscore character “_” used to start the private gameObject “_laserPrefab”:
public class Player : MonoBehaviour
{
[SerializeField]
private GameObject _laserPrefab;
// Start is called before the first frame update
void Start()
{
}
After saving and updating the environment, the field returns in the Inspector view, but is not set to Laser.
Perform the 1–2–3 of <click> the Player in the Hierarchy, drag the LaserPrefab in the Project over to the Inspector’s Player (Script) Laser Prefab.
Now that the link is in place between the two objects, we can add the code in the Player’s Update method to instantiate laser objects.
void Update()
{
// if I press spacebar
// instantiate clone object
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(_laserPrefab);
}
}
Now with each press of the spacebar, another _laserPrefab is cloned, and each laser is at the same position on the game.
Clicking on each Laser(Clone) in the Hierarchy brings up an Inspector view. Each object can be dragged around the game area.
To create a laser that follows the Player object around, add a comma “,” to view tool tip options for use with the Instantiate method.
Option “4 of 10” allows a parameter of the Player’s Vector3 location and a _laserPrefab rotation Quaternion. This Update method is part of the Player class.
A Vector3 is a special type variable that holds x,y,z position data.
A Quaternion is a special type variable that holds x,y,z rotation data. Quaternion.identity is the default rotation setting for an object on the game space.
void Update()
{
CalculateMovement();
// if I press spacebar
// instantiate clone object
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(_laserPrefab, transform.position, Quaternion.identity);
}
}
This completes the instantiation process inside the Player class.
Now we can create behaviors of the clones with code in the Laser’s class Update method.
<double-click> the Laser from the Scripts list to move to the Visual Studio script’s tab. Make certain to work under the Laser.cs tab, not the Player.cs tab.
Here is some code to move the lazer gameObject up as soon as it appears from instantiation:
public class Laser : MonoBehaviour
{
// need a speed variable about 8
[SerializeField]
private float _speed = 8.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// translate laser upward
transform.Translate(Vector3.up * _speed * Time.deltaTime);
}
}
Each laser continues on an upward path from this code.
It is enough to delete each laser when the top of the camera view is reached. Here is example search results for destroying a gameObject documentation:
“gameObject” does refer to the instance of the lazer object.
“this.gameObject” also refers to the instance of the lazer object calling the Destroy method within the Update(). “8” is the top y-coordinate of the camera view.
// Update is called once per frame
void Update()
{
// translate laser upward
transform.Translate(Vector3.up * _speed * Time.deltaTime);
// if laser object higher than 8, destroy object
if (transform.position.y >= 8.0f)
{
Destroy(gameObject);
}
}
and using “this”:
// Update is called once per frame
void Update()
{
// translate laser upward
transform.Translate(Vector3.up * _speed * Time.deltaTime);
// if laser object higher than 8, destroy object
if (transform.position.y >= 8.0f)
{
Destroy(this.gameObject);
}
}
Here is an example showing the Player cube moving left after three Laser launches.