How to access properties of factory instances

Hi there. Firstly, as this is my first post, greetings! Nice to meet you all.

I’ve just started out with a small practice project to get the hang of Defold as I’m working through some tutorials, but I’ve come up against my first problem.

I want to create some moving asteroids on my screen, so I’ve created a factory and I’m writing the factory script. I want each asteroid to have a velocity property so that later on in my update loop I can move each asteroid instance at a different speed. I figured it would also be a good idea to store the id of each factory instance in an array so I can access them later.

Here’s what I’ve got so far:

function init(self)
    self.idArray = {}
    for n = 1, 20 do
        local id = factory.create('/asteroids#factory', position, rotation, {velocity = math.random() * 5}, scale)
       table.insert(self.idArray, id) 
    end
end

Now, in the update function, how do I access the velocity property of each instance? I can get the ID’s from my array, but it seems that to get a property from a game object I need its url rather than just its ID.

This is what I have so far in my update function:

function update(self, dt)
    for n = 1, 20 do
        id = self.idArray[n]

        local velocity = go.get(what goes here? , 'velocity')
    end
end

Many thanks in advance!

1 Like

There might be a simpler way, but I think this should work as your “what goes here?”:

msg.url(nil, self.idArray[n], "name_of_the_script_attached_to_it")

What you need is the url pointing to the script, rather than just the game object.

More can be found here.

Thanks for your response Klear.

When you say ‘name of script attached to it’, do you mean the id of the script I’m currently writing - ie. the script that’s creating the factory instances?

If so, then using your example, I’m writing this:

local url = msg.url(nil, self.idArray[n], "asteroidScript")
local velocity = go.get(url , 'velocity')

I think I understand the principle, but it’s giving me this error, pointing to the second line of the above code:

could not find component 'asteroidScript' when resolving '(null)'

So I’m still confused. What exactly is ‘null’ here?

Not sure about the null there, but you need to address it to the script attached to the asteroid that’s spawned by the factory rather than your current script.

Hmmm, the asteroid spawned by the factory doesn’t have a script attached to it. Should it have? And what should go in it?

Ah … I think I’m beginning to grasp the idea here, so if I add a prototype script to the prototype asteroid, then I can set the velocity property and update its position there, rather than in the factory script. Yep, that works! Thanks for your help!

And here: Factory component manual

2 Likes