Whether you are spawning enemies or loot, almost every game needs some sort of spawning system. In this tutorial, we are going to learn how to build a random spawner script.
First we need to define what our script is going to do. You can some it up with the four points below.
- Keep Track of Spawning Locations and Items
- Pick What Location to Spawn
- Pick What Item to Spawn
- Actually Spawn the Item
Now that we know exactly what our script is going to do, we can move onto the next step.
Now the fun part. We will break up the four points in the planning stage above to make it easier to tell what part of the code does what.
Keeping Track of Locations & Items
This can be done fairly easily. All we need is a list of transforms that holds our spawning locations and another that holds the items.
Picking Locations and Items
We can use a handy Unity function called Random.Range to help us. If given an two integers it chooses a random integer between those two values, non-inclusive.
Using this function we can simply call this function and use that as the index value in our Location/Item list. Note that the code below isn’t usable, as its just showing how to use Random.Range in this circumstance.
Spawning the Items at the Locations Chosen
This code defines a function that allows us to chose how many items to spawn.
Putting it All Together
With all these parts put together, we have a complete and usable, spawning script.
If you want to test it without calling it from another script, you could add the code below. It makes a button and text field so you can test spawning the number of objects you want.
That concludes this tutorial on how to make a spawning script. If you liked this tutorial, make sure to follow us on twitter to get notified when we post new content (like this)!