GLTFFileLoader Observable and typescript

Hello, and this is mostly an issue with typescript, but I would appreciate any advice. I am looking to emulate the functionality of the following playground: https://playground.babylonjs.com/#ARN6TJ#5 and am stuck with the anonymous functions being used by the loader observables.

The following code:

BABYLON.SceneLoader.OnPluginActivatedObservable.addOnce(function (loader) {
    // This is just a precaution as this isn't strictly necessary since
    // the only loader in use is the glTF one.
    if (loader.name !== "gltf") return;

    // See what the loader is doing in the console.
    loader.loggingEnabled = true; 
}

Causes the following error at build time:

TS2339: Property ‘loggingEnabled’ does not exist on type ‘ISceneLoaderPlugin | ISceneLoaderPluginAsync’.
Property ‘loggingEnabled’ does not exist on type ‘ISceneLoaderPlugin’.

How would the same function be written in typescript? I have so far been unable to cast the loader to a GLTFFile type for using withing the function.

Thanks for any help or resources,
r

You would need to cast it as BABYLON.GLTFFileLoader but it seems the Playground does not recognize this class whereas it does exist in the namespace:

image

Maybe @bghgary will know more.

Hello, and thanks for helping with this. It looks as if the issue I am causing is coming from mixing ES5 and ES6 styles.

The loader can be included using the following import statement:
import {GLTFFileLoader} from “@babylonjs/loaders/glTF”;

And the fix you suggested is working:
SceneLoader.OnPluginActivatedObservable.addOnce(loader => {
if (loader.name !== ‘gltf’) return;

        var gltf = loader as GLTFFileLoader;
        gltf.loggingEnabled = true;
        // (loader as GLTFFileLoader).useRangeRequests = true;
    });

Is there are cleaner way to achieve the type cast? Or a way to perform the cast on the input when the function is declared?

Example (not working):
SceneLoader.OnPluginActivatedObservable.addOnce((loader as GLTFFileLoader) => {
loader.loggingEnabled = true;
});

r

Try instead:

SceneLoader.OnPluginActivatedObservable.addOnce((loader: GLTFFileLoader) => {
    loader.loggingEnabled = true;
});

I think this doesn’t work either since it’s the wrong way cast. Maybe try this:

SceneLoader.OnPluginActivatedObservable.addOnce((loader) => {
    if (loader instanceof GLTFFileLoader) {
        loader.loggingEnabled = true;
    }
});

Note that instanceof is somewhat slow, but shouldn’t be an issue here since it’s called infrequently.

1 Like

Hey, and thanks to you both for answering. I ended up doing the following:

    SceneLoader.OnPluginActivatedObservable.addOnce(loader => {
        if (loader.name !== 'gltf') return;

        var gltf = loader as GLTFFileLoader;
        gltf.loggingEnabled = true;
    }

I was unable to cast the input type, but this works instead.
r

1 Like