Unity: Instantiating and destroying gameobjects

Before I write the code for instantiating an object, I need to create a prefab of the object.

In this example I have created and resized a capsule, renamed it ‘Laser’ and then dragged it to my Prefabs folder in the Project pane.

First I’ll add a serialized gameobject to the player script I created in an earlier article. This will allow us to assign the prefab to be instantiated.

Now that we have a laser, let’s get the code in place to instantiate it. I want to create a new laser every time the space is pressed down.

Every time the space bar is pressed, Instantiate() is called. It uses our assigned prefab and creates or instantiates it, at the position of the object the script is attached to, in this case, our player.

The result is that we now create a laser at the position of the player whenever we press the space bar.

Next I create a new script in Unity called Laser and attach that to the Laser prefab.

I’ve added a simple translate to the laser script so that once created, the laser will move up at the rate of the _laserSpeed/per second.

Now the lasers travel up from the player when instantiated.

Currently these lasers will continue to exist until the game is stopped. Let’s destroy the lasers when they leave the screen.

I’ve added an if statement to update that checks if the laser is at or above 8 on the y axis, and, if so it calls Destroy(). I’ve explicitly defined it as this.gameObject in order to avoid any potential future issues with destroying game objects.

Now you can see that the lasers are automatically removed when the move off screen.

--

--

--

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.

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

Recommended from Medium

Let’s create a CRUD REST API with Spring Boot, JPA, and H2.

Ballerina Hello World: The IntelliJ Style!

Fail Fast or: How to make life of your development team easier

OFAC Checker: most advanced OFAC checking solution

OFAC Checker is a Salesforce-native app that performs unlimited OFAC checks on individuals and entities, either automatically or manually, from any standard or custom Salesforce object.

SQL’s comeback — Had it ever left?

A love letter to hackathon from an intern

Introducing Ambassador Cloud Developer Edition

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
Ian Plumpton

Ian Plumpton

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.

More from Medium

Making The Point With Primitives

Creating an Office Den in Unity Part 2: Lights, Cookies and Emissions

Unity Performance Optimization Ⅴ: Lua Scripts Optimization

Making a RTS game #49: Optimisation tips & tricks (Unity/C#)