Same entity script on multiple entities


#1

I’m having tons of issues with running the same script on multiple entities. It seems to me that only the most recent entity the script was loaded on works. Preload, which sets my entityID to a variable, is set to the most recent reloaded entity script entityID no matter what entity the script is on. Sorry if this is confusing, please ask any questions for clarification.

I’m mostly just wondering, is it possible for me to run two entities with the same script and have them completely separate with the data inside them.


#2

There is a few things one has to wrap their head around when developing entity scripts and entity server scripts vs just standard scripting on the client scripts / js scripts in general.

When you set an entity script, the entity script expects an anonymous function that returns an object to keep context: Boiled down something akin to:

(function(){
  console.log("I am my own instance, but I dont know who I am");
  var context =  {
    preload: function (id){
      console.log("I was loaded by entity " + id + " I am it now");
    }
  };
  return context;
})

I suggest reading up more on the thread on the subject:


#3

// When script is first loaded, Everything outside here are first things called. Global
// For All local instances of this script
(function(){
function MyObject(){
// Can be used a constructor, define all the
// variables in here instead of below where they are shared among all the instances of the entity
}
MyObject.prototype = {
preload: function(entityId){
// When an entity has been loaded into the world, this is triggered.
}
}
// This is called every time a new object is created with this script
return new MyObject()
}) // Either use this or a return at the very end of the file.

In this example you say “// Can be used a constructor, define all the // variables in here instead of below where they are shared among all the instances of the entity.” Does this mean that variables here are local to each entity running the script and that variables in preload won’t be unique for each instance of the script, but rather global to all entities running the script? Or am I reading this totally wrong?


#4

All the entity scripts are running on the same script engine instance. So you have to wrap them in a function or their variables will overwrite each other.


#5

Okay thank you. That answers one question. So another question is, if I write “Script.update.connect(_this.update);” it seems that it’s only running for the most recently loaded script. Is that true? Is this where my problem lies? If so, is there a way around it?