[SOLVED] Initialize: function () syncronizes with all instances

Not sure, if my topic name is correct, but anyway…

I’m a newbie here, so I ran into problem.

I have a .js script, that spawns some asteroids on my scene. My code look like this:

var asteroid = new pc.Entity(); // Create new Entity
          app.root.addChild(asteroid); // Add to the scene
          asteroid.addComponent("script", {
             scripts: [{url: 'Asteroid.js'}]
          }); // Add script component
          asteroid.addComponent("model", {
              type: 'box'
          }); // Add a box model

And here is the script (Asteroid.js) I add to my new Entity:

pc.script.attribute('rotSpeed', 'number', 0.1, {
decimalPrecision: 2
});

var astRot;

pc.script.create('Asteroid', function (app) {
// Creates a new Asteroid instance
var Asteroid = function (entity) {
    this.entity = entity;
};
var astRot;

Asteroid.prototype = {
    // Called once after all resources are loaded and before the first update
    initialize: function () {
        this.astRot = [
            Math.round(pc.math.random(-1,1)), // * this.rotSpeed,
            Math.round(pc.math.random(-1,1)), // * this.rotSpeed,
            Math.round(pc.math.random(-1,1)) // * this.rotSpeed
        ]; // Asteroid rotation vector
    },

    // Called every frame, dt is time in seconds since last update
    update: function (dt) {
            

        console.log(astRot);
        this.entity.rotateLocal(astRot[0],astRot[1],astRot[2]); // Rotate the asteroid every tick.
        
    }
};

return Asteroid;
});

As you can see, I have astRot variable, that have rotator array inside. Values for this rotator set inside initialize function. But the problem is, that as soon as new asteroid spawns, initialize function calls and it changes astRot inside ALL instances of my asteroid.

So, how can I change my variable only inside one instance independently?

Looks like there is a bit of confusion here with where you are declaring your variables.

In your initialize method: this.astRot = ... is declaring a variable on the script instance. This is unique per entity.

Outside of the prototype you are declaring: var astRot; This variable is declared once for all scripts.

In your update method this.entity.rotateLocal(astRot[0]...) you are using the global variable.

In short: remove the var astRot; line and in your update method use this.astRot instead of astRot.

Thank you very much. Now I see what I did wrong :smile: