Так что вы могли бы сделать, например, сохранить их в Словаре, например
private Dictionary<int,Dictionary<int,Coroutine>> routines = new Dictionary<int, Dictionary<int,Coroutine>>();
Так что внешний словарь - это группа подпрограмм, внутренний словарь связывает каждую подпрограмму с уникальным подпрограммойInIndex в этой группе.
Таким образом, когда вы запускаете подпрограмму, вы передаете 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);
}
. упростите задачу вместо int
для groupIndex. Вы можете заменить его на enum
, например,
public enum GroupID
{
GroupA,
GroupB,
etc
}
Примечание. Напечатано на смартфоне и не проверено, но я надеюсь, что идея становится ясной