Drop rate / rarity
I want to drop items with a rarity factor but only one at a time.
I have this at the moment:
int rarity = Random.Range (0, 101);
for(int i = 0; i < theCurrency.Length;i++ )
{
if( rarity >= theCurrency[i].DropRarity)
{
Instantiate(theCurrency[i].coinPrefab,transform.position,transform.rotation);
}
}
The problem is, if rarity is 0 for example, all items get dropped, instead of just the lowest which has a rarity of 5.
How can i fix it?
Comment
Best Answer
Answer by OctoMan · Nov 19, 2015 at 02:44 PM
This seems to be a valid solution
int itemWeight = 0;
for(int i = 0; i< theCurrency.Length;i++)
{
itemWeight += theCurrency[i].DropRarity;
}
int randomValue = Random.Range (0, itemWeight);
for(int i = 0; i< theCurrency.Length;i++)
{
if(randomValue <= theCurrency[i].DropRarity)
{
Instantiate(theCurrency[i].coinPrefab,transform.position,transform.rotation);
return;
}
randomValue -= theCurrency[i].DropRarity;
}
Answer by _Game_Dev_Dude_ · Nov 19, 2015 at 02:19 PM
Right after your instantiate add the following.
break;
Basically you are looping through all the items and seeing if they are bigger than zero, if they are spawn them. So once you find an item that satisfies the conditions you need to stop looping. Break stops your for loop.
Yeah but the problem remains. The droprate does not work right. But i think i found the solution.