How do I add a script to a mesh?

How to add script code to mesh?

You create a mesh in Javascript, assign it to a variable and then assess that variable to change properties of the mesh.

What I mean is that I created a JS script and wanted to attach it to the mesh, just like in the editor

How about assigning your custom update() function to Object3D.userData? In the animation loop, you can then traverse through the scene and then call update() for an object if present.

1 Like
  • Could you give me a demo? Thank you very much

Something like this: Edit fiddle - JSFiddle - Code Playground

Full code:

let camera, scene, renderer;

let mesh;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 4;

    scene = new THREE.Scene();

    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshNormalMaterial();

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );
    
    mesh.userData.update = function() {
    
    	mesh.rotation.y += 0.01;
    
    };

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    scene.traverse( updateCallback );

    renderer.render( scene, camera );

}

function updateCallback( object ) {

	if ( object.userData.update !== undefined ) object.userData.update();

}
2 Likes