[SOLVED] How To Change A Variable From Another Script

I want to make a script to attach to a trigger area that returns the grounded variable on my player to false. Seems simple enough, but one problem. I don’t know how to change the variable from another script. I’ve tried a couple of ways, but I just can’t seem to change a variable from an external script. My question here is, what is the proper way to change a variable from an external script?

Hi @DevPlex01,

The most straightforward way is to get a reference to the entity holding that other script instance and follow this pattern:

entity.script.myScriptName.myPropertyName;
  • myScriptName, you can find this by clicking in your script asset after you parse it. This is the script type name as registered when parsed.
  • myPropertyName, this should be the name of the property you are trying to update in your script. Note you can’t access local variables, only properties like this:
this.playerName = 'aName'; 

So does this mean I can access attributes but not normal variables?

What do you mean with “normal variables”?

You can access anything that is a property of the this object which includes attributes.

Oh ok, I think i get it now.

Also you can use events if you only wants to set the state of other variable and not to get it.

1 Like

Indeed events are quite powerful and it’s my preferred way of communicating between scripts. Here is a simple example:

ScriptA.prototype.initialize = function(){
   this.myProperty = 'nameA';

   this.app.on('change:name', function(newName){
      this.myProperty = newName;
   }, this);
};

ScriptB.prototype.initialize = function(){
   this.app.fire('change:name', 'nameB');
};
1 Like

Events good for interface alternative, direct variable most preferable. Many events many ruined perfomance ((