puerts_unity_demo
puerts_unity_demo copied to clipboard
ts协程能支持吗 StartCoroutine
public* ResourcesAsync(path: string, callback: Function)
{
UnityEngine.Debug.Log("ResourcesAsync start");
var resourcesRequest: UnityEngine.ResourceRequest = UnityEngine.Resources.LoadAsync(path);
yield resourcesRequest;
UnityEngine.Debug.Log("ResourcesAsync end");
var prefab = resourcesRequest.asset as UnityEngine.GameObject;
callback(prefab);
}
var rs = this.ResourcesAsync("Sphere", (prefab: UnityEngine.GameObject) => {
UnityEngine.Object.Instantiate(prefab);
});
rs.next();
rs.next();
这些在ts里面写,有时unity跑了就崩溃,而且rs.next();是同步加载资源,不是异步。CS里面StartCoroutine是异步。有没有ts里面写协程StartCoroutine... yield return... 的方法,求大佬帮忙
尽量使用async function实现功能(WWW/UnityWebRequest下载等), 使用Unity协程涉及大量的跨语言调用, 从性能考虑这不是一个好的选择
csharp代码
using System;
using System.Collections;
using Puerts;
public static class IEnumeratorUtil
{
public static IEnumerator Generator(Func<object> next, Func<bool> isDone)
{
var done = false;
while (!done)
{
yield return next();
done = isDone();
}
next = null;
isDone = null;
}
public static IEnumerator Generator(Func<Tick> next)
{
Tick tick = new Tick() { done = false };
while (!tick.done)
{
tick = next();
yield return tick.value;
}
next = null;
}
public static void UsingTick(this JsEnv jsEnv)
{
jsEnv.UsingFunc<Tick>();
}
public struct Tick
{
public bool done;
public object value;
public Tick(object value, bool done)
{
this.value = value;
this.done = done;
}
}
}
typescript代码
/**创建C#迭代器 */
function cs_generator(func: ((...args: any[]) => Generator) | Generator, ...args: any[]): CS.System.Collections.IEnumerator {
let generator: Generator = undefined;
if (typeof (func) === "function") {
generator = func(...args);
if (generator === null || generator === undefined || generator === void 0)
throw new Error("Function '" + func?.name + "' no return Generator");
}
else {
generator = func;
}
return CS.IEnumeratorUtil.Generator(function () {
let tick: CS.IEnumeratorUtil.Tick;
try {
let next = generator.next();
tick = new CS.IEnumeratorUtil.Tick(next.value, next.done);
} catch (e) {
tick = new CS.IEnumeratorUtil.Tick(null, true);
console.error(e.message + "\n" + e.stack);
}
return tick;
});
}