Tencent / puerts

PUER(普洱) Typescript. Let's write your game in UE or Unity with TypeScript.
Other
5.01k stars 699 forks source link

[Unity] Bug: new JsEnv() can't be always called on a separate thread in the Editor #1847

Open DoctorGester opened 6 days ago

DoctorGester commented 6 days ago

前置阅读 | Pre-reading

Puer的版本 | Puer Version

2.1.0

Unity的版本 | Unity Version

2023.1.13f1

发生在哪个平台 | Platform

Editor(mac)

错误信息 | Error Message

No response

问题重现 | Bug reproduce

This highly depends on installed packages, but JsEnv constructor calls TypeManager.InitArrayTypeId(); which in turn calls Puerts.Utils.GetExtensionMethodsOf(typeof(Array)). Certain packages seem to call Unity-specific methods in their static constructors which produces an error when called outside of the main thread.

We have this hack in the main thread before launching a Thread which creates JsEnv

    private void MaybeInitializePuertsHack() {
        // Workaround to run JsEnv on a separate thread, otherwise it tries to discover some extension methods
        //  of Array class which trigger static init of things which can only be initialized on the main thread, sigh...
        // Only seems to happen in the editor though
#if UNITY_EDITOR
        if (!initializedPuertsHack) {
            Puerts.Utils.GetExtensionMethodsOf(typeof(Array));
            initializedPuertsHack = true;
        }
#endif
    }

We don't need reflection at all because all of our methods are registered from the generated source bindings but it seems like there is no way to turn off discovery of extension methods specifically for Array class when in the editor. It also produces a huge multi-second delay for us.

image