Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
    }
like image 839
Zik Lebovsky Avatar asked Nov 23 '25 18:11

Zik Lebovsky


1 Answers

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.

like image 94
Tomasz Juszczak Avatar answered Nov 26 '25 17:11

Tomasz Juszczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!