2

In Three.js I want to create an object and then add a variable to it. I'm sure it's simple but I can't seem to do it, nor work out how to do it.

For example, I create a cube, and I want it to store a variable "beenHit" that can then be accessed in a Raycast.intersectObjects later on.

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var newColor = new THREE.Color("rgb(12%, 6%, 0%)");
var material = new THREE.MeshStandardMaterial( { color: newColor } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
var cube.beenHit = false;

Is clearly wrong, but I've tried different ways and searched quite a bit, but my feeble brain cannot compute. Any help most appreciated.

1 Answer 1

4

You can use the object THREE.Object3D.userData.

cube.userData.beenHit = false;

But

cube.beenHit = false;

without var

Can do the trick too. Remember that THREE.Object3D are nothing more than JavaScript objects, you can store anything you want as long as you don't override Three.js properties.

Edit

As Martin pointed out, you should always use userData or you might encounter compatibility issues in the future.

Sign up to request clarification or add additional context in comments.

2 Comments

cube.userData.beenHit is a correct, if you use cube.something = foo, you can have compatibility problems in future.
Thanks, that makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.