Spawning Game Objects with Instantiate

David Hunter Thornton
3 min readAug 11, 2022

--

How do I spawn in a game object in Unity?

Objective: Explain how Unity uses “Instantiate” to spawn or create objects.

Now that we’ve created “Bullets” for our 2D “Shoot ’em Up” we need to cause those bullets to spawn by pressing a button. There are two previous articles needed before starting this one. One dealing with Prefabs and another with the Input Manager of Unity.

If you’ve come directly from my last article, the first thing I need you to do is delete the “Bullet” prefab from the Hierarchy. We don’t want to get this Bullet mixed up with the rest of what we’re doing. This will create problems down the line.

Now that we’ve prevented a future confusion, we need to associate our Bullet prefab with our Player Character. We’re going to use “SerializeField” again to create a box where we can attach the two.

This tells our script to create a location called “Bullet Prefab” in the inspector, where we can drag and attach a Game Object. Be better than me though, don’t forget to include an underscore in front of “bulletPrefab;”. As a reminder, this is the industry standard for private variables.

Now, we just need to tell it to actually spawn the object. For this, we’re going to use an “if” statement, to gather whether or not the user presses down on a key. You could callout the spacebar specifically, but for now, we’re just going to use “Fire1”. But this will require changing the button prompt in “Fire1”. There’s another article on this here.

There’s two different ways you can check if a button has been pressed. You can check if it has been pressed and then released, and you can also check if the button is still being held down. This is counter-intuitive to what you might think.
Input.GetButton = See if a button is being held down each frame
Input.GetButtonDown = See if a button was pressed each frame

The only part above that I haven’t previously gone over is “Quaternion.identity”. Quaternion is Unity’s method for measuring rotation. And the “identity” part simply means to take the default based on the parent object, in this case, our Player Character.

As you can see every time I place the space bar I spawn a new “clone” of the original bullet prefab. In the next article, I’ll be talking about giving some velocity to those bullets.

Friendly Reminder: Don’t forget to keep updating your project through GitHub/Git and saving any changes you make to a separate branch. You can check out my other articles to get a breakdown of those steps! Day 1–9

--

--