babylon.js how to get access to a mesh outside of it's function

旧巷老猫 提交于 2021-01-05 11:20:41

问题


I just cant get access to the babylon mesh. Everytime I try to run the code I get this error.

I've tried it with two different approaches:

Example 1:

var carTest;
BABYLON.SceneLoader.ImportMesh("", "assets/", "car.obj", scene, function(object) {
        carTest = object[0];
    });
carTest.position.x = 10;

Example 2:

var carTest = BABYLON.SceneLoader.ImportMesh("", "assets/", "car.obj", scene);
carTest.position.x = 10;

回答1:


In your example 2, The BABYLON.SceneLoader.ImportMesh return Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>, and both of them do not have property name as position.
Thus, carTest.position would be undefined.

carTest.position.x = 10 => undefined.x = 10; 

will throw error.

In your first example, BABYLON.SceneLoader.ImportMesh is a synchronized function, although there is another function name ImportMeshAsync in BABYLON.SceneLoader...

I have not used BABYLON before.
But basically, according to BABYLON API, the difference between ImportMesh and ImportMeshAsync is the returned type.

so,

[Improvement]

move carTest.position.x = 10; in your onSuccess callback.

BABYLON
  .SceneLoader
  .ImportMesh("", "assets/", "car.obj", scene, function(object) {
        carTest = object[0];
        carTest.position.x = 10;
    });



回答2:


When call SceneLoader, the carTest object only are set when return the onlyne (function), then the object are not ready in the next line (carTest do not exist at this time).

You need await to use carTest object when SceneLoader are finish.




回答3:


Instead of using the synchron method with callback function you could use the async function if you know the concept of async / await.

Example:

const data = await SceneLoader.ImportMeshAsync("", "assets/", "car.obj", scene);
const carMeshes = data.meshes;

If you know there is only one with children you could access [0] otherwise you may need to merger the meshes. Depends on what you want to do.



来源:https://stackoverflow.com/questions/62018719/babylon-js-how-to-get-access-to-a-mesh-outside-of-its-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!