Instantiating & Destroying Gameobjects in Unity

Lance Gold
7 min readMar 18, 2024

--

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.

Right click to begin with creating a new 3D Object, a Capsule

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.

The new object’s name should be entered quickly to match the created Object Class

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.

Creation of a Prefabs folder to hold the new Asset GameObject

<drag> the Lazer object into the Prefab list folder

The Prefab Laser object is ready for pairing with components

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.

One common Component is a Material, later to be a Component color

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.

When choosing a Material, a common name adds “_mat” to the prefab Object name

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.

The “Apply All” Override connected the component to the object and its clones

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.

Searching for Instantiation and Destroying documentation often uses docs.unity3d.com

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.

Inside the commanding object’s script, the prefab clone is instantiated

Looking at keyboard access, there are choices: press, up, down. Then there is a keycode.

Within the Update method is the input.GetKeyDown method
    // 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.

In the Unity environment, console messages appear at the bottom left of the window

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:

The 1–2–3 of linking a Prefab Laser to a Player object

After the drag:

After the link made showing “Laser” in the Inspector view Laser Prefab view

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:

Inspector view with hidden private laser gameObject

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.

Inspector view without linked serialized private gameObject

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.

Player object’s Inspector view showing linked Laser Prefab object after drag and drop.

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.

Hierarchy view with multiple Laser clone objects after each spacebar keypress

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.

The choice “4 of 10” to code the Instantiate() method. Note the underscore character to name the object variable
The Instantiate method parameters of object name, position, and Quaternion rotation.
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.

Example game run with several instantiated cloned laser capsules

Now we can create behaviors of the clones with code in the Laser’s class Update method.

Access the prefab Laser script with a double click

<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.

View of the prefab Laser script in Visual Studio

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:

Example friendly documentation explaining the use of gameObject with the Destroy method
Example of docs.Unity documentation after a search for the Destroy method use
Helpful search result to detail the use of the gameObject parameter with Destroy method

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.

Game view of Player cube moving while launching three Laser(Clone) objects

--

--

No responses yet