How to get custom class object from a mesh

I have a custom class that creates a mesh and is added to the scene. If I click the mesh how do I get the class object that created the mesh?

Do I need to store the class object in the mesh? Something like this?

this.mesh.metadata = {};

this.mesh.metadata.parent = this;

So that when the mesh is clicked I can access the class that created it?

If I’m understanding correctly, you just want to associate some app-specific object with a Babylon Mesh so that when it is clicked and your callback is executed, you can map that Mesh back to your own associated object, is that right?

If so, you could plop your object into the metadata, or you could just set it as a property directly on the Mesh (possibly using a Symbol if you want to guarantee your property won’t collide with another property), or you could use a WeakMap so store an association between the Mesh and your custom object.

Simple way

class MyThing {
    public mesh: BABYLON.Mesh;

    constructor(scene: BABYLON.Scene, name: string, position: BABYLON.Vector3) {
        this.mesh = BABYLON.MeshBuilder.CreateSphere(name, { diameter: 2 }, scene);
        this.mesh.position = position;

        // attach reference to this class
        this.mesh.metadata ??= {};
        this.mesh.metadata.owner = this;
    }

    public onClick() {
        console.log("Clicked MyThing instance:", this);
    }
}

Example - Babylon.js Playground

1 Like