当前位置:网站首页>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;
}
}
边栏推荐
- Space shooting lesson 14: player life
- Explain rigid body and collider components in unity
- Huawei cloud digital asset chain, "chain" connects the digital economy, infinite splendor
- 作业 ce
- The average altitude is 4000 meters! We built a cloud on the roof of the world
- 如何用Redis实现事物以及锁?
- h5微信射击小游戏源码
- Two written interview questions about regular
- Using viewpager to slide through pages in fragment
- Oracle库访问很慢,是什么原因?
猜你喜欢

太空射击第10课: Score (繪畫和文字)

Prize essay solicitation | 2022 cloud native programming challenge draft activity opens

PL515 SOT23-5 单/双口 USB 充电协议端口控制器 百盛电子代理商
![[C language brush questions] explanation of linked list application](/img/44/1de4e3f0712780680fbdc904dfe39a.png)
[C language brush questions] explanation of linked list application

Space shooting Lesson 10: score (painting and writing)

js飞入js特效弹窗登录框

卡通js射击小游戏源码

What is data center? What value does the data center bring_ Light spot technology

Job CE

The cloud native programming challenge is hot, with 510000 bonus waiting for you to challenge!
随机推荐
Leetcode:2141. The longest time to run n computers at the same time [the maximum value is two points]
Teach you unity scene switching progress bar production hand in hand
C# 读取 CSV文件内数据,导入DataTable后显示
What is data center? What value does the data center bring_ Light spot technology
有奖征文 | 2022 云原生编程挑战赛征稿活动开启
C# 委托 delegate 的理解
Dynamic planning: code summary of knapsack problem template
什么是数据中台?数据中台带来了哪些价值?_光点科技
[complete collection of common ADB commands and their usage (from a comprehensive summary of [wake up on Sunday)]
About the title of linking to other pages
云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
Space game Lesson 12: shield
Seventeen year operation and maintenance veterans, ten thousand words long, speak through the code of excellent maintenance and low cost~
研发效能的思考总结
EasyNLP中文文图生成模型带你秒变艺术家
网络各层性能测试
Unity gadget displays the file size of the resource directory
Confusing knowledge points of software designer examination
激光slam:LeGO-LOAM---代码编译安装与gazebo测试
Subcontracting loading of wechat applet