Variable losing value

I don’t understand why my Vec3 is losing its value.

The entities are generated in code and given a position. When the entity is initialised, it stores its position in ‘originalPosition’

When the entity is clicked it is detected with a raycast and calls the entities clicked() function. When that function is called the Vec3 originalPosition has changed to (0,0,0)

    pc.script.create('selected', function (app) {
    var originalPosition = new pc.Vec3();

    // Creates a new Selected instance
    var Selected = function (entity) {
        this.entity = entity;

    Selected.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            originalPosition = this.entity.getPosition();
            console.log("originalPositionInit" + originalPosition + this.entity.getGuid()); 
        clicked: function(){

            console.log("originalPositionClicked" + originalPosition + this.entity.getGuid());

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


    return Selected;

The variable originalPosition is declared outside of the script instance. So there is only one originalPosition for all Entities with this script attached. Are you creating many entities with this script?

If so you should store the position as a member of the Selected class.


initialize: function () {
    this.entity = entity;
    this.originalPosition = this.entity.getPosition();

Thanks, this.originalPosition fixed it.

I see, yes I wanted individual instances. So entities with the same script can share variables defined outside class.prototype?

And this.entity = entity; should stay in the constructor right?

Yes, sorry this.entity was a mistake.

That script and the function passed to pc.script.create are called just once for the application, so variables declared in there are shared. Then the script object you defined will be created one for each entity with the script attached.

1 Like