Creating & Destroying objects in Unity

One of the foundations of creating a game, is the ability to create and destroy game objects. Doing so is a fairly straight forward process in Unity.

To begin you will need an object to create and/or destroy. You can either import your own object or create one using one of Unity’s built in objects.

We’ll start with creating an object. Create a script in Unity and attach it to an object in the scene.

Double click on the script so we can edit it.

Creating an object at runtime in Unity is referred to as “Instantiation” and we will be instantiating an object with the press of the space bar:

In this instance, we used 3 arguments to instantiate the bullet…the “_bullet” which is the game object, the “transform.position” which is the current position of the object and the rotation. Quaternion.identity simply means a rotation of zero.

We need 2 more things in order for this to work. First we need to create our “_bullet” variable at the top of the script:

“SerializeField” gives us access to an object in the inspector while keeping the object private

We have created an object, but how do we destroy it?

We can do that with one line:

You can either add a time argument or simply leave it as is or set a condition of distance or trigger to call this.

With little setup you can see how easy it is to run something like this:




Unity Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

DynamoDB — Aggregate or Realtime calculating (Part3)

Memoization in Haskell

Connecting to Snowflake using Python and Java — Part II

My Venture Into Information Technology.

Report your AWS Costs programmatically using the Cost Explorer API

Fourth Project: Javascript

Spring Boot Microservices — Part2 — config-server and RefreshScope with RabbitMQ

How to update Jenkins build status in GitHub pull requests [Step-by-Step Tutorial]

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mike Brisson

Mike Brisson

Unity Developer

More from Medium

Unity and Variables❤

Switch Statements to the Rescue

Drawing rectangles

Infinite Runner in 3 Steps