例如,您可以将它们存储在字典中,例如
private Dictionary<int,Dictionary<int,Coroutine>> routines = new Dictionary<int, Dictionary<int,Coroutine>>();
所以外层字典是一组例程,内层字典将每个协程链接到该组中唯一的routineIndex。
所以当你开始一个例程时,你传入IEnumerator 和你想要开始它的组索引。
然后例程本身嵌套在一个通用工作例程中执行,该例程通过 groupIndex 和例程索引从routines 字典中自动删除相应的例程:
public void StartRoutine(int groupIndex, IEnumerator routine)
{
if (!routines.ContainsKey(groupIndex))
{
routines.Add(groupIndex, new Dictionary<int, Coroutine>());
}
// Get next available index within group
var routineIndex = 0;
while (routines[groupIndex].ContainsKey(index))
{
routineIndex++;
}
routines[groupIndex].Add(routineIndex, StartCoroutine(Worker(routineIndex, index, routine)));
}
// pass in the group and routine index
// so each worker "instance" knows exactly
// which entry to remove from the routines
// Dictionary when it is done
private IEnumerator Worker(int groupIdx, int routineIdx, IEnumerator routine)
{
yield return routine;
// when done remove from dictionary
routines[groupIdx].Remove(routineIdx);
}
现在您可以通过使用例如组索引停止所有例程
public void Stop(int groupIdx)
{
if(!routines.ContainsKey(groupIdx)) return;
foreach (var routine in routines[groupIdx].Values)
{
StopCoroutine(routine);
}
routines.Remove(groupIdx);
}
为了让事情变得更简单,而不是 groupIndex 的 int,您可以将其替换为 enum,例如
public enum GroupID
{
GroupA,
GroupB,
etc
}
注意:在智能手机上输入并未经测试,但我希望这个想法变得清晰