Godot-StartUP

创建于:2018-07-28

创建人: Justus

44 信息 150 成员
讨论基于Godot以及Unity引擎的游戏开发经验,理论和最佳实践。共享一些通用思路以启发另一种生产工具中的实践。独立开发群QQ: 122017359

[译]在godot中利用yield函数来使用协程(Coroutines)

Justus 2018-07-30

Coroutines with yield

GDScript 提供yield内建函数用以支持coroutines。调用yield()将会立刻从当前函数返回,同时将这个函数的当前状态冻结作为返回值。如果之后通过返回值得到的对象调用resume(继续)方法,就会继续从上个冻结状态执行下去并返回下一个返回值。一旦调用过resume方法后,之前的得到的状态对象就失效了。例子如下:

func my_func():
   print("Hello")
   yield()
   print("world")

func _ready():
    var y = my_func()
    # Function state saved in 'y'.
    print("my dear")
    y.resume()
    # 'y' resumed and is now an invalid state.

输出结果:

Hello
my dear
world

yield()resume()调用之间我们也可以传递参数,例子如下:

func my_func():
   print("Hello")
   print(yield())
   return "cheers!"

func _ready():
    var y = my_func()
    # Function state saved in 'y'.
    print(y.resume("world"))
    # 'y' resumed and is now an invalid state.

输出结果:

Hello
world
cheers!

Coroutines & signals

与signal(信号)机制结合使用才会发挥yield真正的长处。 yield方法可以接受两个参数,一个对象引用,一个信号名称。效果是:收到该信号时,重新开始执行该协程。例子如下:

# Resume execution the next frame.
yield(get_tree(), "idle_frame")

# Resume execution when animation is done playing.
yield(get_node("AnimationPlayer"), "finished")

# Wait 5 seconds, then resume execution.
yield(get_tree().create_timer(5.0), "timeout")

协程本身使用名为completed的信号来表达他们转移进入了一个无效状态,例子如下:

func my_func():
        yield(button_func(), "completed")
        print("All buttons were pressed, hurray!")

func button_func():
    yield($Button0, "pressed")
        yield($Button1, "pressed")

my_func仅当两个button按钮都被按过以后才会继续执行。

参考

  1. [GodotDocs] GDScript
  2. [Wikipedia] Coroutine
  3. [Wikipedia] Subroutine
(转发自:原日志地址

近期喜欢的会员

 

加入 indienova

  • 建立个人/工作室档案
  • 建立开发中的游戏档案
  • 关注个人/工作室动态
  • 寻找合作伙伴共同开发
  • 寻求线上发行
  • 更多服务……
登录/注册