My 90 day journey becoming a Unity game developer: Day-5

Rhett Haynes
2 min readMay 27, 2021

Objective: Create simple enemy movement and have the enemy respawn randomly along the X-axis. This is the final result:

Enemy respawns randomly along the X-axis.

To start, create an enemy using a cube. Scale it down to 0.75 to make it a little smaller than the player. Afterward, create a material, change the color to red, and attach the material to the enemy. Then make the enemy cube a prefab by dragging the enemy into your Prefab folder.

Create an enemy script called Enemy. Attach it to the enemy prefab, were we will make the enemy move in a downward motion. Create a variable called speed to have the enemy move 4 meters down per second. Inside Update() function, use the following code to have the enemy moving down along the Y-axis:

Enemy moves down along the Y-axis.

Now when the enemy moves below the screen, we will respawn the enemy at the top of the screen in a random range between -8f and 8f along the X-axis. We use float with the random range because if you use integers, the maximum value which is 8 will return 7 instead and this would not use the entire right side of the screen. This is the code that will allow this to happen:

Enemy respawns at the top of the screen on the X-axis and Y-axis.

Lets make this code more efficient by creating a variable randomX to hold the random range to use along the X-axis. This will make it easier to read the code:

Enemy spawning at a random range on the X-axis using a variable to execute the random calls.

Next time we will work on destroying the enemy and using trigger collisions.

--

--