Unity Developer — Spawn Percentage

To add variety to our game, we have made numerous types of enemies and of powerups. Some of the enemies are tougher than the others and some of the powerups are more helpful than the others. So it would make sense for both of these to spawn less than the others. Here’s how we can change the spawning percentages, rather than make them all equal.

Previous to this, when spawning multiple types, we would write something along the lines of ‘int randomType = Random.Range(0, 6);’ if 6 was the number of types. In this case, each number would be as likely to appear as the other. This is exactly what we are going to change.

First off, we are going to change that line of code to ‘float randomType = Random.Range(0.0f, 1.0f);’ Now the value can be anything from 0 to 1 and this can be easily split into percentages. The same could be done with 0 to 100 as well. Use what makes more sense to you.

We are going to be using a long IF-ELSE Statement now. Before that be sure to declare an int for the type number. This will be the value we assign to know what will be instantiated.

Now all you have to do is split up the 0 to 1, or 0 to 100, by percentages depending on what you want spawned more or less. Here is an example.

So enemyType 0 has a 35% chance of spawning, but enemyType 1 has only a 10% chance. If you set up your types in an array and with the Inspector, you can use this number value to instantiate.

Now you can make extremely weak enemies or bigger and tougher ones and you’ll know how to balance accordingly.




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

Recommended from Medium

Containerizing Dotnet Core Apps With Docker

Creating Events that are queueable and handle them with Supervisor

Monitoring Snowflake with Snowsight

DIY Stream Deck with Raspberry Pi and 5'’ Touch Screen

Configure Web Server and Launch Python Interpreter On The Top Of Docker Container

Monitoring your system: or how I stopped worrying and learned to love the dumpster fire

How to get started with coding (and 2 blunders to avoid)

How to Style any Input Field – Tips and Techniques

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
Christopher Graf

Christopher Graf

More from Medium

From Prototype to Work of Art

I think you dropped something — Creating a simple loot drop system in Unity2D

Install Unity’s new input system

How We Implemented Vehicle Mechanics in Our Game — Part 4