关于unity3d:Unity(C#)-> Kotlin <-协程

Unity (C#) -> Kotlin <- Coroutines

我第一次在Kotlin进行实验,希望能提供一些帮助。

下面的代码要做的是暂停当前函数的执行,而不会休眠正在执行的线程。 暂停基于提供的时间量。 该功能通过使用C#语言的Coroutine支持来工作。 (此支持最近也已添加到Kotlin中!)

Unity示例

1
2
3
4
5
6
7
8
9
10
11
12
void Start()
{
    print("Starting" + Time.time);
    StartCoroutine(WaitAndPrint(2.0F));
    print("Before WaitAndPrint Finishes" + Time.time);
}

IEnumerator WaitAndPrint(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint" + Time.time);
}

我还没弄清楚如何在Kotlin中做类似的事情。 有人可以帮我指引正确的方向吗? 如果在发布答案之前弄清楚了,我会更新我的帖子。

提前致谢!


请记住,协程是Kotlin 1.1的一部分,而Kotlin 1.1仍在EAP中(早期访问预览)。虽然我个人已经取得了巨大的成功,但该API仍然不稳定,您不应该依赖它在生产环境中工作。同样,当Kotlin 1.1最终定稿时,此答案可能会过时。

  • 如果尚未安装,请按照此博客文章底部的说明,将项目和IDE升级到最新的Kotlin 1.1 EAP里程碑(在撰写本文时为M04)。
  • 查找或编写将执行您想要的功能。

    • kotlinx.coroutines有很多,尽管在这种情况下不是您想要的。
    • 幸运的是,事实证明编写非阻塞睡眠非常容易:
  • 1
    2
    3
    4
    5
    6
    7
    private val executor = Executors.newSingleThreadScheduledExecutor {
        Thread(it,"sleep-thread").apply { isDaemon = true }
    }

    suspend fun sleep(millis: Long): Unit = suspendCoroutine { c ->
        executor.schedule({ c.resume(Unit) }, millis, TimeUnit.MILLISECONDS)
    }

    有一些重要的警告需要注意。与.NET相比,所有可挂起方法将由某个地方的某个共享中央池处理(老实说,我什至不知道在哪里),上面链接/所示的示例睡眠方法将在执行器池中运行所有继续的工作,您指定。上面链接的示例sleep方法使用单个线程,这意味着sleep之后发生的所有工作将由单个线程处理。对于您的用例而言,这可能还不够。

    如果您对Kotlin协程的详细信息还有其他疑问,我强烈建议您在kotlinlang闲暇时加入#协程频道。有关加入的详细信息,请参见此处。


    这几乎是使用kotlix.coroutines库将C#Unity代码逐行转换为Kotlin协程的结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    fun main(args: Array<String>) {
        println("Starting" + Instant.now())
        launch(CommonPool) { waitAndPrint(2.0f) }
        println("Before waitAndPrint Finishes" + Instant.now())
        // Kotlin coroutines are like daemon threads, so we have to keep the main thread around
        Thread.sleep(3000)
    }

    suspend fun waitAndPrint(waitTime: Float) {
        delay((waitTime * 1000).toLong()) // convert it to integer number of milliseconds
        println("waitAndPrint" + Instant.now())
    }

    您可以通过示例来了解更多关于kotlinx.coroutines的信息,该示例包含更多类似的示例,它展示了Kotlin coroutines的各种可用功能,而不仅仅是无阻塞的睡眠。