简体   繁体   中英

Using async await in Unity

Someone can say how to make such a construction work? Currently returns UnityExtension. Well, or advise how easy it is to move a part of the non-MonoBehaviour code into a separate thread.

UnityException: get_canAccess can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

    private async void Awake()
    {
        Mesh protoMesh = gameObject.GetComponent<MeshFilter>().mesh;
        SelfMesh = await InitMeshAsync(protoMesh);
    }

    protected async Task<CustomMesh> InitMeshAsync(Mesh protoMesh)
    {
        return await Task.Run(() => new CustomMesh(protoMesh.vertices, protoMesh.triangles));
    }

By the look at the exception, CustomMesh is using code that is not able to run form separate thread. protoMesh.vertices, protoMesh.triangles needs to be fetched before you start new thread.

private async void Awake()
{
    Mesh protoMesh = gameObject.GetComponent<MeshFilter>().mesh;
    SelfMesh = await InitMeshAsync(protoMesh);
}

protected async Task<CustomMesh> InitMeshAsync(Mesh protoMesh)
{
    var vertices = protoMesh.vertices;
    var triangles = protoMesh.triangles;
    return await Task.Run(() => new CustomMesh(vertices, triangles));
}

As what can be run from a separate thread and what not is tricky, and you need to constantly see how given field/method is implemented, but a good rule of thumb would be to always copy the requested field of a base type like int , string , float[] before you start another thread.

If you would go to the GitHub you would see that vertices uses GetAllocArrayFromChannel which uses GetAllocArrayFromChannelImpl which is native method whom cannot be used from separate thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM