- Home /
Random drop rate problem
var itemDrop : GameObject;
var enemyHealth : int = 1;
var dropRate : float = 0.25; //25% chance of dropping
function OnCollisionEnter(theCollision : Collision)
{
if (theCollision.gameObject.tag == "Player")
{
enemyHealth -=1;
if(enemyHealth <= 0)
{
Destroy(gameObject);
if(Random.Range(0,1) <= dropRate)
{
var pickupDrop = Instantiate(itemDrop, gameObject.transform.position, Quaternion.identity);
}
}
}
}
Above is the code I have for my random drop rate, when I destroy my enemies I would like it to have a 25% chance of dropping my item, but as I have it now, it happens all the time.
Can anyone point out where I'm going wrong please?
Answer by Jun Hin · Apr 05, 2014 at 12:12 PM
Your Random.Range numbers need to be floats, not integers. So your if statement should look like this: if(Random.Range(0f,1f) <= dropRate)
Answer by HarshadK · Apr 05, 2014 at 12:13 PM
Because your Random.Range function takes integers as input it returns an integer. And as per this page Random.Range script reference, it is always outputing zero, which is always less than dropRate.
Hence, you always get a drop.
Use float values for min and max range to get random float number.
Cheers!
Your answer
Follow this Question
Related Questions
How to make a random team chance? 1 Answer
Random Range BUT only on specific Co Ords 1 Answer
Clean way for percentages 0 Answers
Same prefab getting instantiated for the different items 0 Answers
Script not working (Java script) 2 Answers