Edit factory created object variables globally

I am creating a lot of objects with a factory. And I want to change a variable of all objects.
Example if I produce enemies, and initally they have health = 100 and after a while I want all enemies health become 120 at the same time. Any idea?

Storing enemy information in a central shared Lua module would be an option. You have other options too such as having each enemy script subscribe to messages published by a manager.

See https://github.com/britzl/ludobits/blob/master/ludobits/m/broadcast.md

2 Likes

This is what I am looking for. I will try it! Thanks for the information :relaxed:

Edit: the :slight_smile:

You can track the created objects and use message passing to communicate with them:

-- enemy_spawner.script

-- post a message to all enemies
local function post_to_enemies(self, message_id, message)
	for _,id in ipairs(self.enemies) do
		msg.post(id, message_id, message)
	end
end

-- create an enemy instance and keep track of it
local function create_enemy(self)
	local id = factory.create("#enemyfactory")
	table.insert(self.enemies, id)
end

function init(self)
	self.enemies = {}

	-- create 100 enemies
	for i=1,100 do
		create_enemy(self)
	end

	-- post a message to all enemies
	post_to_enemies(self, "change_health", { health = 150 })
end

Another option is to use a script property for the health on the enemies and use the same principle as above but instead of using message passing you use go.set() to change the health on the script instances of the enemies. If you have the id you can construct the url to the script on the enemies like this:

local enemy_script_url = msg.url(nil, id, "script_id_here")
go.set(enemy_script_url, "health", 150)

A third option is to not have an enemy script at all and track all info about the enemies in a Lua table:

-- enemy_spawner.script

-- create an enemy instance and keep track of it
local function create_enemy(self)
	local id = factory.create("#enemyfactory")
	self.enemies[id] = {
		health = 100
	}
end

function init(self)
	self.enemies = {}

	-- create 100 enemies
	for i=1,100 do
		create_enemy(self)
	end

	-- change health of all enemies
	for id,data in pairs(self.enemies) do
		data.health = 150
	end
end

Using this option where you don’t have a script on the enemies is the most efficient and it is a very good approach if you have a lot enemies. But you need to move and otherwise manipulate the enemies from this central script.

2 Likes

Thanks a lot. Very detailed and great answer.