Attach script to element

Hi, I would like to create a game, but following the concept “attach the script to element.”
For example. In unity, we could create a 3d element Box. Then we can create a script called “MovingBox.cs” Then we have the ability to “attach that script” to the Box. How does this concept work behind de scenes?
I think it makes usages of the concept “dependency injection” but I am not sure.
Thanks for any help.

Hello this is more C# than javascript in mind :slight_smile:
We do have behaviors for that: Behaviors - Babylon.js Documentation

Welcome btw!!!

1 Like

Hi and welcome,

Good question. This answered well 10 years ago at a JS conference, by Venkat S.

He said (in a thick indian accent):

“Objects are like backpacks.”

“There is no ceremony in JavaScript”

“You just put what you need in the backpack”

“It will not shout at you.”

It still makes me smile.

Here is what I do, as a result of his advice.

let ns = {}
ns.scene = BABYLON.createScene()

ns.scene.addAnything = true;

nx.scene.extraCams = {};
nx.scene.extraCams.skyCam1 = nx.createSkyCam();

//To your question
let aBackpack = BABYLON.createSphere();

aBackpack.anythingYouWantAttachedToMesh = function(){ /*script*/}

aBackpack.anythingYouWantAttachedToMesh();

:eagle: : )