using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; using Random = UnityEngine.Random; namespace Ichni { public static class GeneralExtensions { public static void Invoke(this Dictionary dictionary) { foreach (var action in dictionary.Values) { action.Invoke(); } } public static void Invoke(this Dictionary> dictionary, T arg) { foreach (var action in dictionary.Values) { action.Invoke(arg); } } public static void Invoke(this Dictionary> dictionary, T1 arg1, T2 arg2) { foreach (var action in dictionary.Values) { action.Invoke(arg1, arg2); } } /// /// 遍历列表中的每个元素并执行指定的操作,用于foreach不能遍历的情况,例如在foreach中删除元素 /// public static void For(this IList list, UnityAction action) { for (int i = 0; i < list.Count; i++) { action.Invoke(list[i]); } } /// /// 将列表中的元素从此列表转移到另一个列表 /// public static void Transfer(this List fromList, List toList, T item) { if (fromList.Contains(item)) { fromList.Remove(item); toList.Add(item); } else { Debug.LogError($"Item {item} not found in this List."); } } /// /// 在列表中交换两个元素 /// public static void Swap(this IList list, int i, int j) { (list[i], list[j]) = (list[j], list[i]); } /// /// 随机打乱列表中的元素 /// public static void Shuffle(this IList list) { for (int i = 0; i < list.Count; i++) { list.Swap(i, Random.Range(i, list.Count)); } } /// /// 随机获取列表中的元素 /// public static List GetRandomElements(this List list, int count) { List randomElements = new List(); if (count >= list.Count) { randomElements = new List(list); return randomElements; } List randomIndices = new List(); while (randomIndices.Count < count) { int randomIndex = Random.Range(0, list.Count); if (!randomIndices.Contains(randomIndex)) { randomIndices.Add(randomIndex); randomElements.Add(list[randomIndex]); } } return randomElements; } /// /// 删除所有满足 predicate 的键值对。 /// public static void RemoveWhere(this IDictionary dict, Func predicate) { dict.Where(pair => predicate(pair.Key, pair.Value)).Select(pair => pair.Key).ToList().ForEach(key => dict.Remove(key)); } /// /// 获取所有子物体 /// public static List GetAllChildren(this Transform parent) { return parent.Cast().ToList(); } } }