当前位置:网站首页>C # basic 7-iterator and coroutine
C # basic 7-iterator and coroutine
2022-07-28 20:55:00 【W.C.Zeng】
iterator
The iterator method uses yield return Statement returns the element , One at a time . arrive yield return When the sentence is , Will remember the current position in the code . The next time you call the iterator function , Execution will restart from this location .
Use iterators to iterate over collections
arr.GetEnumerator() Acquisition iterator e.MoveNext() If the current iteration has reached the last element , return false ; otherwise true , Iterator iterates once e.Current The element pointed to by the current iterator
int[] arr = new int[]{
1,2,3};
IEnumerator e = arr.GetEnumerator();
wihle(e.MoveNext())
{
Console.WriteLine(e.Current);
}
Or use forEach Loop through an iteratable set ( IEnumerable ) Every element of
Print the results
1
2
3
coroutines
With c# The iterator , Can understand unity In the process of cooperation
Reference reading B Station article unity coroutines
The next big segment is to realize similar unity Contents of the cooperation process Reference resources Zhihu netizens' articles
Use iterators 、 Double linked list 、 Thread sleep , simulation unity The realization of the middle process
The logic is more complicated , You can't figure it out until you debug it several times
The main function only needs to start the coroutine , It is enough to continuously update the coordination process
static void Main()
{
Console.WriteLine("[Main] start");
CoroutineManager.Instance.Start(CoroutineTest());
int framecount = 0;// Simulate the current number of frames , At present time Next ,1 second 50 frame
while (true)
{
// Print the current number of frames
framecount++;
Console.WriteLine("[Main] cur framecount:<" + framecount + ">");
// Update the execution process every frame
CoroutineManager.Instance.UpdateCoroutine();
// simulation unity Of update wait for 20
Thread.Sleep(Time.deltaMilTime);
// The first 35 When the frame Exit procedure
if (framecount >= 35)
break;
}
}
Write a collaborative process , wait for 0.5 second , Wait for 3 frame
// Co process test function
private static IEnumerator CoroutineTest()
{
Console.WriteLine("[CoroutineTest] begin yield return waitforseconds:0.5f");
yield return new WaitForSeconds(0.5f);
Console.WriteLine("[CoroutineTest] begin yield return waitforframe:3");
yield return new WaitForFrame(3);
Console.WriteLine("[CoroutineTest] exit");
}
Refer to the netizen code to realize , Collaborative process management , Maintain the bidirectional linked list of the collaboration class
public class CoroutineManager
{
// Singleton field
private static CoroutineManager _instance = null;
// Singleton properties
public static CoroutineManager Instance
{
get
{
if (_instance == null)
_instance = new CoroutineManager();
return _instance;
}
}
/// The linked list stores all collaboration objects
private LinkedList<Coroutine> coroutineList = new LinkedList<Coroutine>();
private LinkedList<Coroutine> coroutinesToStop = new LinkedList<Coroutine>();
/// Start a process
public Coroutine Start(IEnumerator ie)
{
var c = new Coroutine(ie);
coroutineList.AddLast(c);
return c;
}
/// Close a collaboration
public void Stop(Coroutine coroutine)
{
Console.WriteLine(" Collaboration manager - Stop the process ");
coroutinesToStop.AddLast(coroutine);
}
/// The main thread drives all co process objects
public void UpdateCoroutine()
{
var node = coroutineList.First;
while (node != null)
{
var coroutine = node.Value;
bool ret = false;
if (coroutine != null)
{
// Whether the coordination process is in the stop state
bool toStop = coroutinesToStop.Contains(coroutine);
if (!toStop)
{
// Update the execution position of the collaboration , Once the collaboration object returns false, It means that we have traversed to the end , The process is about to exit
ret = coroutine.MoveNext();
}
}
if (!ret)
{
// When the coroutine traverses to the end , Stop the process
coroutine.Stop();
coroutineList.Remove(node);
Console.WriteLine("[CoroutineManager] remove coroutine");
}
// Iterate over the next node in the linked list
node = node.Next;
}
}
}
Realization IWait Interface , Judge whether the waiting conditions are met
// simulation unity Medium WaitForSeconds WaitForFrame
public class Time
{
// One second 50 frame
public const float deltaTime = 0.02f;
public const int deltaMilTime = 20;
}
public interface IWait
{
bool Tick();
}
public class WaitForSeconds : IWait
{
public float waitTime = 0;
public WaitForSeconds(float time)
{
waitTime = time;
}
bool IWait.Tick()
{
waitTime -= Time.deltaTime;
Console.WriteLine("[WaitForSeconds] now left:" + waitTime);
return waitTime <= 0;
}
}
public class WaitForFrame : IWait
{
public int waitFrame = 0;
public WaitForFrame(int frame)
{
waitFrame = frame;
}
bool IWait.Tick()
{
waitFrame--;
Console.WriteLine("[WaitForFrame] now left:" + waitFrame);
return waitFrame <= 0;
}
}
Define a coroutine class , A coroutine class is essentially a container for iterators
public sealed class Coroutine
{
// Iterator class
private IEnumerator _routine;
// Constructors
public Coroutine(IEnumerator routine)
{
_routine = routine;
}
// The iterative method of moving to the next iteratible position
public bool MoveNext()
{
if (_routine == null)
return false;
// Look at the iterator's current process control ( namely yield return Objects behind )
// Is it our current IWait object , If it is , See if you're satisfied with moveNext Conditions
IWait wait = _routine.Current as IWait;
bool moveNext = true;
// If it is IWait Just count down and wait
if (wait != null)
// count down
moveNext = wait.Tick();
if (!moveNext)
{
// When the time is not up , return true
// Tell the collaboration manager There are still objects to be iterated next time
Console.WriteLine("[Coroutine] not move next");
return true;
}
else
{
// At this time, all waiting times or frames have been iterated , see IEnumerator Whether there are any subsequent objects yield return object
// Notify the manager of this result , The manager will decide whether to continue the iteration at the next iteration Coroutine object
Console.WriteLine("[Coroutine] move next");
return _routine.MoveNext();
}
}
public void Stop()
{
Console.WriteLine(" Process stop ");
_routine = null;
}
}
边栏推荐
- What is data center? What value does the data center bring_ Light spot technology
- 【1331. 数组序号转换】
- Unity package project to vs deploy hololens process summary
- Unity package exe to read and write excel table files
- JS picture hanging style photo wall JS special effect
- 什么是数据中台?数据中台带来了哪些价值?_光点科技
- Redis入门一:Redis实战读书笔记
- Huawei cloud digital asset chain, "chain" connects the digital economy, infinite splendor
- How to balance security and performance in SQL?
- Looking at SQL optimization from the whole process of one query
猜你喜欢

Space shooting Lesson 15: props

Thinking and summary of R & D Efficiency

Three deletion strategies and eviction algorithm of redis

Space shooting Lesson 10: score (painting and writing)

Explain in detail the rays and radiographic testing in unity

Unity typewriter teaches you three ways

prometheus配置alertmanager完整过程

H5 wechat shooting game source code

js网页黑白背景开关js特效

Ask if you don't understand, and quickly become an advanced player of container service!
随机推荐
C# 读取 CSV文件内数据,导入DataTable后显示
Ask if you don't understand, and quickly become an advanced player of container service!
js网页黑白背景开关js特效
Yum package management
Explain rigid body and collider components in unity
Redis入门一:Redis实战读书笔记
Integrating database Ecology: using eventbridge to build CDC applications
Two written interview questions about regular
C# 委托 delegate 的理解
[工具类] Map的util包, 常用 实体类转化为map等操作
Fragment中使用ViewPager滑动浏览页面
JS drag and drop alert pop-up plug-in
Mongoose condition queries part of the data of the specified attribute
全链路灰度在数据库上我们是怎么做的?
"When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
如何平衡SQL中的安全与性能?
想画一张版权属于你的图吗?AI作画,你也可以
Algorithm interview high frequency problem solving guide [1]
The cloud native programming challenge is hot, with 510000 bonus waiting for you to challenge!
一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力