Changing variables to change weapons

Let’s go back to your script. Thinking critically and following the logic of your code is very important to avoiding frustration. I’m going to use the version posted:

PlayerAttachments.prototype.initialize = function() {
    this.weapon = this.current;
    var weapon = current;
    var current = this.entity.findByName('m4');
    
    this.rhand = this.entity.findByName('mixamorig1:RightHand');
    this.scaleOffset = 100;
    //reparentLockTransform (this.current, this.rhand, this.scaleOffset);
    reparentLockTransform( this.weapon, this.rhand, this.scaleOffset);
};

This is what happens when your script is initialized:

  • You create a ‘variable’ (actually called a prototype, but for this case and for your understanding it’s the same) called this.weapon and make it equal to the currently undefined this.current
  • You create a var called weapon and make it equal to the currently undefined this.current
  • You create a var called current and make it equal to a search for a child entity called ‘mp4’
  • You create a ‘variable’ called this.rhand and make it equal to a search for a child entity called ‘mixamorig1:RightHand’
  • You create a ‘variable’ called this.scaleOffset and make it equal to 100
  • You call the function reparentLockTransform() and pass the arguments this.weapon, this.rhand, and this.scaleOffset

If you follow along these steps, hopefully you will realize that this.weapon is failing because this.current was never defined which means that this.weapon is also undefined.

If you define this.current properly at the top of the function (like you define var current) it will work when you pass it along to reparentLockTransform()

2 Likes

Will I be able to change the value even if I define it as a “findByName”

A definition on any variable only lasts as long as it isn’t redefined. If you make it equal to a ‘findByName()’ function it is then equal to that entity.

If later in your script (say after a keypress happens) you say that ```this.current = somethingElse``, then it is equal to something else.

I would highly recommend spending some additional time looking at general Javascript tutorials or lessons as they can be helpful in clearing ideas like these up.

1 Like

Hmm, apparently i can’t have code to define the same code more than once

I think the best thing you can do now, is look at your code (and post if if you like) and explain out loud what each line is doing. If you can’t explain what that line is doing, you might want to look at it more closely, or consider removing it and working your way from the top of the function to the bottom again, recognizing what each line does and thinking about how it aligns with your goals.

1 Like

Ok