如何避免while循环引起的游戏冻结?(How can i avoid game freezes caused by while loop?)

编程入门 行业动态 更新时间:2024-10-25 11:20:58
如何避免while循环引起的游戏冻结?(How can i avoid game freezes caused by while loop?)

我正在研究RRT路径寻找系统。 基本上,它会生成随机点以查找路径。 我成功完成了它但遇到了严重的问题。 在生成这些点时,我使用的是while语句,它需要大约10,000到15,000次循环迭代。 正如你猜测的那样,它将游戏冻结1-2秒。 我想在我的while语句中使用yield但是如果我是对的,当我使用它时,我的while循环每帧会工作一次。 然后,如果我有60 fps,那么完成循环时需要250秒。 这是不可忽视的。 所以我的问题是:如何在没有任何游戏冻结的情况下完成循环?

I am working on RRT path finding system. Basically, it generates random points to find a path. I finished it successfully but am faced with a serious problem. While generating these points I am using a while statement and it takes around 10,000 - 15,000 loop iterations. As you might guess, it freezes the game for 1-2 sec. I thought to use yield for my while statement but if I am right, when I use that, my while loop will work one time per frame. Then if I have 60 fps, it will take 250 seconds to finish this while loop. This is impossible to ignore. So my question is: how can I finish this while loop without any game freezes?

最满意答案

正如Chanibal所说,线程仍然是可能的。 我当然不是在吹嘘这是完成你所追求的最好的方法,但由于你似乎对索林的答案不太热衷,我想我会提到你仍然可以使用一个屈服声明。

单循环迭代后,您不必屈服。 一个例子:

int i = 0; while (yourCondition) { if (++i % 100 == 0) yield return null; }

这在每100次迭代后产生。 有许多其他方式有条件地屈服,你只需要决定什么最适合你的情况。

As Chanibal stated, threading is still possible. I'm certainly not touting this the best way to accomplish what you are after, but since you didn't seem too keen on Sorin's answer, I thought I'd mention that you can use a yield statement still.

You don't have to yield after a single loop iteration. One example:

int i = 0; while (yourCondition) { if (++i % 100 == 0) yield return null; }

This yields after every 100 iterations. There are a myriad of other ways to conditionally yield, you just need to decide what best fits your situation.

更多推荐

本文发布于:2023-08-07 20:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:游戏   avoid   game   loop   caused

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!