- Home /
How to make Random.Range() step by a certain amount?
I doubt that the title alone is enough information to understand the question I'm asking, so I'll ask by example:
In my game my enemies have a certain minSpawnHealth and maxSpawnHealth variable which determines the current health of my enemy on spawn. This way when the enemies spawn they can have a randomized amount of health between the min and the max. In order to find that randomized health I'm using "Random.Range(minSpawnHealth, maxSpawnHealth+1)", which is pretty standard.
However, I want the returned value of Random.Range() to step by a certain amount, say 5 or 10.
Let's say that minSpawnHealth is 10 and maxSpawnHealth is 30, so that a new enemy could spawn somewhere between 10-30 health. I don't want my enemy to have the possibility of spawning with 13 health, or 17 health, or 26 health, etc. I would want my enemy to spawn with health by intervals of 5 (10, 15, 20, 25, 30 health) or 10 (10, 20, 30 health), or whatever arbitrary step amount I would want Random.Range() to return.
Is there any inherent way to do this (which I haven't found yet) or do I just have to be clever with math adjustments after the randomized value is created?
Answer by pslattery · Aug 21, 2017 at 10:28 PM
I think the simplest way to do this would be:
int minSpawnHealth = 10;
int maxSpawnHealth = 30;
int stepSize = 5;
int GetRandomHealth () {
int randomHealth = Random.Range(minSpawnHealth, maxSpawnHealth);
int numSteps = Mathf.Floor (randomHealth / stepSize);
int adjustedHealth = numSteps * stepSize;
return adjustedHealth;
}
Works very well and can be applied outside of this question scope, thank you!
Your answer
Follow this Question
Related Questions
Non-repeating random number generator crashing unity 1 Answer
Need help with generating random Multiplier,Need help with generating random multipliers 0 Answers
How to make enemy prefab spawn at random times between 1.0f to 10.0f. 1 Answer
How can I randomly create a number and then delete it to stop repeating 3 Answers
Distribute terrain in zones 3 Answers