コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】List からランダムに値を取得して、その値を List から削除する拡張メソッド

ソースコード

using System.Collections.Generic;
using UnityEngine;

public static class ListExt
{
    public static T PopRandomElement<T>( this List<T> self )
    {
        var item = self[ Random.Range( 0, self.Count ) ];
        self.Remove( item );
        return item;
    }
}

使い方

var list = new List<int> { 1, 2, 3, 4, 5 };
var value = list.PopRandomElement();