The same script in several game objects is executed only for the last added one. What to do? (SOLVED)

(Sorry for the English, I use a translator)
I’m trying to make a platformer. There was a need to make primitive opponents-so that they went from wall to wall (as in most platformers). Since I try Defold after Unity, I implemented everything like this: I created one script that handles the movement of the mob, which I plan to put in all enemies, with similar behavior.
However, when I have one game object-everything works well. But it is worth adding more game objects, as a result, all the code seems to be executed only for the last added one.
Through debugging, I was able to understand that at first the execution of scripts works as it should, the first two seconds, but then the values of variables in their own functions eventually take the values of variables for the last object.
For example, I output the coordinates of an object by X - in the init function, the correct values are output to the console, but now only the value for the last game object is output from its own functions.
Does Defold need to be implemented in some other way?

If you make your variables global, they will be shared between all instances of a script. However, the self variable is specific to the instance, so you want to use that for things like storing velocity and position.

Examples

-- Velocity will be the same between all instances of this script
local velocity = vmath.vector3()

function init(self)
   -- This will also be shared between instances
   position = go.get_position()
end
...
function init(self)
   -- This will be separate for each instance
   self.velocity = vmath.vector3()
...
3 Likes

Local variables are shared with all instances of a script. You need to store them as self.

A detailed explanation can be found here.

5 Likes

Thank you all for your help! I used self variables, but I didn’t do it for all values, so it didn’t work)

Note that using self is much slower than using local variables. This can become an issue if there are many instances and the self variables are used many times per frame.

2 Likes

Thank you for warning me! I was just thinking about it. Fortunately, my project will have fewer than 30 objects with similar behavior at the same time.

1 Like