It will most likely work well in most cases. I’m merely offering another solution which will be more efficient in some situations where you have many objects. Here’s modified code which shows a bit of what I mean:
local function add_card(self, position, data)
local component = "/cardInstance#card_factory"
print("Card name: " .. tostring(data.name))
local go_id = factory.create(component, position, nil, nil, .3)
table.insert(self.cards, {
id = go_id,
data = data,
})
end
local function remove_card(self, id)
for i,card in ipairs(self.cards) do
if card.id == id then
go.delete(id)
table.remove(self.cards, i)
return
end
end
error("Unable to find card!")
end
-- factory.script
local function generate_cards(self, _, response)
-- store list of cards here
self.cards = {}
local data = json.decode(response.response)
local p = go.get_position()
-- looping over the cards
for k, v in pairs(data) do
p.x = p.x + 200
v.score = 10 -- why isn't the score in the data?
add_card(self, p, v)
end
end
local function do_stuff_with_cards(self)
local total_score = 0
for _,card in ipairs(self.cards) do
go.animate(card.id, "euler.z", go.PLAYBACK_ONCE_FORWARD, 360, go.EASING_INOUT_QUAD, 1)
total_score = total_score + card.score
end
print(total_score)
end
function init(self)
http.request("http://localhost/mygame/cards.json", "GET", generate_cards)
end
Another example where you want this approach is in for instance a shoot’em up game where you may have hundreds of bullets. You don’t want a script on each bullet to handle bullet movement. You want a single bullet handler that moves the bullets. And in the simple case of moving bullets in a straight line you’d use go.animate() and maybe not even a bullet handler.