Dennis Liu Dennis Liu - 28 days ago 9
C# Question

How To Show Item With Item Given Percentage ? Unity C#

I got problem on scripting the game in unity using C#.
I want to get the item which have a percent.

For example I have a

List<item> Bonus
below :

ITEM | QTY | PERCENT


  1. Coin 20 100%

  2. Coin 40 95%

  3. Coin 300 40%

  4. Coin 700 10%

  5. apple 2 60%

  6. Lemon 2 60%

  7. orange 2 60%

  8. Wood 1 90%

  9. wood 2 70%

  10. wood 3 50%

  11. Silver Bar 1 4%

  12. Fish meat 2 60%

  13. Saw 1 7%

  14. Rope 1 7%



The percent item show the chance to show up.

How to get 1 item from that with percentage ?
How it be in c# ? Is it enough for the detail ?

Thanks

Dennis

Answer

The way I understand your question is you'll have :

  • 100% chances to get 20 coins
  • plus 95% chances to get 40 coins
  • plus 40% chances to get 300 coins
  • ...

This way you'll have to do something like this :

List<items> itemsWon = new List<item>();
float randomPercentage = Random.Range(0.0f, 1.0f);
for(int i = 0; i < Bonus.Count; i++)
{
    if (randomPercentage > Bonus[i].PERCENT)
    {
        itemsWon.Add(Bonus[i]);
    }
}

But considering your comments I'd say you only want to win 1 of those items. In this case you have to give each item and int value (easier than working with floats in this case) let's say your PERCENT property and do something like this :

items itemWon;
int totalItemsPercent = 0;
for(int i = 0; i < Bonus.Count; i++)
{
    totalItemsPercent += Bonus[i].PERCENT;
}

int percentToReach = Random.Range(0, totalItemsPercent + 1);
int itemsPercentSum = 0;
for(int i = 0; i < Bonus.Count; i++)
{
    itemsPercentSum += Bonus[i].PERCENT;
    if (itemsPercentSum >= percentToReach)
    {
        itemWon = Bonus[i];
        break;
    }
}

Hope those will help you. Also keep in mind posting your already produced code always help others understand what you try to achieve. Regards,