LoginSignup
6
3

More than 3 years have passed since last update.

【C#】配列やリストの中からランダムに1つ返す関数

Last updated at Posted at 2020-06-09

はじめに

Unityを使っていると 複数のオブジェクトの中から1つの要素を同様に確からしい確率で取得したい という場面が多々ある。
アイテムのランダムドロップやガチャがその場面に該当する。

この処理の実装自体は簡単なのだが以下の問題がある。

  • 配列の中からの取得、リストの中からの取得、どちらにも入っていない集団からの取得で実装方法が異なる
  • 関数を作らない場合はコピペコードが量産される
  • ジェネリックを使わない場合は型ごとに関数を実装する必要がある

今回は上記の問題を解決する関数を作った。

配列やリストの中からランダムに1つ返す関数

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Helper : MonoBehaviour
{
    internal static T GetRandom<T> (params T [] Params)
    {
        return Params [Random.Range (0, Params.Length)];
    }

    internal static T GetRandom<T> (List<T> Params)
    {
        return Params [Random.Range (0, Params.Count)];
    }
}

使用例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log (Helper.GetRandom (1, 2, 3, 4, 5));
        Debug.Log (Helper.GetRandom (new float [] { 0.5f, -1.5f, 9.99f }));
        Debug.Log (Helper.GetRandom (new List<string> () { "aiueo", "12345", "abcde" }));
    }
}

実際に以下のようなログが流れる。
GetRandom_Log

おまけ:配列とリストのみに対応する場合

IList を使えば配列とリストに対応可能。
ただし上の例の Helper.GetRandom (1, 2, 3, 4, 5) はエラーが出る。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Helper : MonoBehaviour
{
    internal static T GetRandom<T> (IList<T> Params)
    {
        return Params [Random.Range (0, Params.Count)];
    }
}

6
3
2

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
6
3