Code Structure: type error undefined object

Hi there,

I’m trying to figure out what’s the best way to structure my code.
At the moment I’d like to define a number of functions before the main createScene() function.
This to keep the code organised and structured, so I can declare all my functions on top of the code, and then call them in the createScene() among others.
This will also allow me to easily turn on and off a number of features in the code, which in my opinion helps to debug more easily.

Any advice on this is more than welcome.
However at the moment I’m having some issues with this kind of layout, because I’m getting errors when some objects or items aren’t declared yet, which could be caused by the way the code is structured.
In the createScene() I’m calling on this func:

CamAutoRotate(scene, "active", true, 4000, 500, 0.8) // (scene, input, io, spinupTime, waitTime, rotSpeed)

This returns the following error:

Below is the code which causes that error.
Also when I try to log my camera’s which is commented out here, I get undefined.
Is this because the camera’s aren’t fully created yet?

// >>> FilterCameras FromList
var CamFilter = function (scene, input) {
    var camLst = [];
    var camAll = scene.cameras;
    // console.log(camAll);
    if (input == "all") {
        var camLst = camAll;
    } else if (input == "active") {
        var camLst = [scene.activeCamera];
    } else {
        for (var c of camAll) {
            if (c.name == input) {
                camLst = [c];
            }
        }
    }
    return camLst
}
// CamFilter(scene, "active") // (scene, input) // (scene, ["all", "active", "CameraName"])

How can I keep working like this while preventing these kind of errors?

Thanks a lot!
Pieter

Hmm, cameras is initialized to an empty array so it shouldn’t be undefined even if you haven’t created a camera yet. And when you create a camera it’s pushed to the array right away.

If you can make a little playground repo to produce the error we can help figure it out better but IDK from the code posted why it would be undefined… :thinking:

EDIT: Maybe try logging the scene parameter too and see if that’s undefined as well.

hi Pieter

Are you using any async functions? Is the scene object empty when it is passed to function?

I don’t think it is the function but rather the timing of it being called. You could test this by putting your first call to this in a setTmeOut. A lot of the time with BabylonJS I find delaying things a frame does wonders.

1 Like

Hi @Blake and @Michael_Prosser,
Thanks for both your responses.

In the mean time I managed to find the error I made, as the issue persisted in the playground (in this one it’s been fixed.

I forgot to add the “scene” because it was still a piece of code from before.

CamFilter(scene, "active")

However I’m very interested in the async workflow, are there good examples related to bjs where I could look into, to get to know this way of working?

Thanks
Pieter

1 Like