Instantiating Obstacles and Enemies at Random Locations

David Hunter Thornton
3 min readAug 16, 2022

--

How do I use Unity to spawn enemies in random places?

Objective: Show the process for spawning an enemy at random positions on the x axis.

Now that we’ve gone through the steps to have a functioning Player Character that can fire bullets, lets give it something to shoot at. There are two things I’d like to add that are going to be fairly similar to one another, an enemy and a “mine”.

The mine will simply drift towards the bottom of the screen and the player can either destroy it, or avoid it. Since that will be the easiest to make, we’ll start there.

Now that I’ve made a “mine” prefab and script, let’s get into the code.
(Repeat the above steps for the enemy if you’re following along.)

I want to spawn the mines and enemies at random positions along the x axis and then have them move downward towards the bottom.

In the above, I’ve used the boundary information I gathered in this article, to set the maximum range for mine and enemy spawning. I’ve declared a float variable so that it can spawn with a decimal value and not just whole numbers. I’ve used “Random.Range()” to mark the specific numerical values possible for the x axis. And finally, I’ve put all of that into a method that can be called immediately at the start of the game. (Repeat the above steps for the enemy if you’re following along.)

Now we just need to use the information in this article to help make it move down to the bottom. (Repeat the above steps for the enemy if you’re following along.)

And the information in the same boundaries article above to cause it to spawn back at the top once it exceeds a certain distance off screen. But this time we’re gonna initiate another random spawn. (Repeat the above steps for the enemy if you’re following along.)

Here’s a look at the finalized code:

Be careful! If we keep going like this we’ll have a real game on our hands soon!

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

--

--