我想在一个组中收集一些协程,这样group.stop()就可以停止所有的协同例程。有没有办法做到这一点?
如果我要手动完成,我会使用一组协程,并且我会包装所有的协程,这样当它们自然完成时,它们就会从集合中删除。但这种包装听起来像是一种性能冲击。
理想情况下,我希望定义一个包含协程的子反应器(MonoBehaviour),然后将子反应器视为协程,允许从主反应器启动和停止它。
谢谢!
发布于 2020-03-23 20:06:53
例如,您可以将它们存储在字典中,例如
private Dictionary<int,Dictionary<int,Coroutine>> routines = new Dictionary<int, Dictionary<int,Coroutine>>();因此,外部字典是一组例程,内部字典将每个协程链接到该组中的唯一routineIndex。
因此,当您启动一个例程时,您需要传入IEnumerator和要在其中启动它的组索引。
然后,该例程本身嵌套在一个通用工作例程中执行,该例程通过routines字典中的groupIndex和例程索引自动删除相应的例程:
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);
}为了让事情变得更简单,你可以用一个enum代替groupIndex的int,比如
public enum GroupID
{
GroupA,
GroupB,
etc
}注意:在智能手机上输入,没有测试,但我希望我的想法变得清晰
https://stackoverflow.com/questions/60812485
复制相似问题