はじめに
Unityを使っていると 複数のオブジェクトの中から1つの要素を同様に確からしい確率で取得したい
という場面が多々ある。
アイテムのランダムドロップやガチャがその場面に該当する。
この処理の実装自体は簡単なのだが以下の問題がある。
- 配列の中からの取得、リストの中からの取得、どちらにも入っていない集団からの取得で実装方法が異なる
- 関数を作らない場合はコピペコードが量産される
- ジェネリックを使わない場合は型ごとに関数を実装する必要がある
今回は上記の問題を解決する関数を作った。
配列やリストの中からランダムに1つ返す関数
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassHelper:MonoBehaviour{internalstaticTGetRandom<T>(paramsT[]Params){returnParams[Random.Range(0,Params.Length)];}internalstaticTGetRandom<T>(List<T>Params){returnParams[Random.Range(0,Params.Count)];}}
使用例
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassTest:MonoBehaviour{privatevoidAwake(){Debug.Log(Helper.GetRandom(1,2,3,4,5));Debug.Log(Helper.GetRandom(newfloat[]{0.5f,-1.5f,9.99f}));Debug.Log(Helper.GetRandom(newList<string>(){"aiueo","12345","abcde"}));}}
おまけ:配列とリストのみに対応する場合
IList
を使えば配列とリストに対応可能。
ただし上の例の Helper.GetRandom (1, 2, 3, 4, 5)
はエラーが出る。
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassHelper:MonoBehaviour{internalstaticTGetRandom<T>(IList<T>Params){returnParams[Random.Range(0,Params.Count)];}}