It will not affect performance to have many factories so from that perspective it really isn’t a problem. But it may become very unwieldy to have hundreds of factories. I would take a more data driven approach.
I would have one enemy.go and one enemy factory. When I spawn a monster I associate the spawned enemy.go with what type of monster it is. You can do this in two ways, one is to use a script property:
-- enemy.script
go.property("type", hash(""))
function init(self)
if self.type == hash("Fly") then
print("I'm a fly")
sprite.play_flipbook("#sprite", "Fly")
elseif self.type == hash("Gaper") then
print("I'm a gaper")
sprite.play_flipbook("#sprite", "Gaper")
end
end
local function spawn_enemy(enemy_type, pos)
local properties = {
type = enemy_type
}
local id = factory.create("#enemyfactory", pos, nil, properties)
return id
end
function init(self)
local fly_id = spawn_enemy(hash("Fly"), vmath.vector3(1,2,3))
end
The other would be to have an enemy manager of some kind which lets you look up what type an enemy is:
-- enemy_manager.lua
local M = {}
local enemies = {}
function M.add(id, enemy_type)
enemies[id] = enemy_type
end
function M.type(id)
return enemies[id]
end
return M
local enemy_manager = require("enemy_manager")
local function spawn_enemy(enemy_type, pos)
local id = factory.create("#enemyfactory", pos, nil, properties)
enemy_manager.add(id, enemy_type)
return id
end
function init(self)
local fly_id = spawn_enemy(hash("Fly"), vmath.vector3(1,2,3))
end
-- enemy.script
local enemy_manager = require("enemy_manager")
function init(self)
local enemy_type = enemy_manager.type(go.get_id())
if enemy_type == hash("Fly") then
print("I'm a fly")
sprite.play_flipbook("#sprite", "Fly")
elseif enemy_type == hash("Gaper") then
print("I'm a gaper")
sprite.play_flipbook("#sprite", "Gaper")
end
end