Search code examples
javascriptbabylonjs

Javascript method not working in BabylonJS with a custom Mesh


I'm very new to BabylonJS and I created a custom Mesh like that (I don't know if it's the right way) :

function DragSphere() {
    this.sphere = BABYLON.Mesh.CreateSphere("sphere", 15, 2, scene);
    this.sphere.material = new BABYLON.StandardMaterial("sphereMat", scene);
    ...
    return (this.sphere);
}

DragSphere.prototype.setRGBColor = function(r, g, b) {
    this.sphere.material.diffuseColor = new BABYLON.Color3(r/255, g/255, b/255);
}

So I want to use the SetRGBColor method of my DragSphere to update its color, but the browser does not seems to agree with me :

 Uncaught TypeError: sphere.setRGBColor is not a function

Solution

  • Remove the return (this.sphere); statement from the constructor.

    If you're using TypeScript only a void function can be called with the new operator. Calling the function with a return type in its signature, as above, will result in the setRGBColor function being undefined in the transpiled JavaScript.

    You can try this out in the Babylon JS playground.