LoginSignup
1
1

More than 5 years have passed since last update.

【Unity】異なる発生確率をもったアイテムを選択する

Posted at

メモ代わりにUnity公式のドキュメントからコピペ

こんな感じの時に使用

  • 50% の確率で親しみやすい挨拶
  • 25% 確率で逃走
  • 20% 確率で急な攻撃
  • 5% 確率でお金をプレゼント
// C#
float Choose (float[] probs) {

    float total = 0;

    foreach (float elem in probs) {
        total += elem;
    }

    float randomPoint = Random.value * total;

    for (int i= 0; i < probs.Length; i++) {
        if (randomPoint < probs[i]) {
            return i;
        }
        else {
            randomPoint -= probs[i];
        }
    }
    return probs.Length - 1;
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1