☑ Unnecessary reference is happening

In the following code

initialize()
{
    this.vec_initTargetPos11 = new pc.Vec3(-2, 0, -2);
    this.vec_targetPos11 = this.vec_initTargetPos11;
}

update()
{
    this. this.vec_targetPos11.x++;
    console.log("vec_initTargetPos11 = " + this.vec_initTargetPos11);
}

this.vec_initTargetPos11 variable is getting updated, even though it is not assigned to this.vec_targetPos11 anywhere.

How is this possible?

if I replace
this.vec_targetPos11 = this.vec_initTargetPos11;
with
this.vec_targetPos11 = new pc.Vec3(-2, 0, -2);
then it works fine.
But why it shouldn’t work as it is in script?
Seems very ridiculous.

1 Like

Vectors are classes so when you assign a vector to another you are just assigning a reference to the vector, you are not making a copy. This is how javascript works.

In your example instead of doing target = initial you should do target = initial.clone()

That way a completely new vector will be created and assigned to the target

1 Like

Hi,
I feel your pain, got caught out by this a few times myself. Best approach I find is to think of everything as a reference rather than a value.

1 Like