Factory names from table?

I have 10 factory game objects. 4 of them I want to spawn randomly in a game during init.

I was thinking of inserting goFactory1, goFactory2, goFactory3… goFactory10 to insert in a randTable . After thet to do a for loop 4 times and inside to call

**factory.create(randTable[math.random(#randTable)], go.set_position(pos))**

However, that doesn’t work.

when I do print randTable[math.random(#randTable)] I am recieving in debugger name of a random factory, but it’s not calling it in factory.create

Please provide some more of your code! How is randTable created for instance? Are you getting an error?

sry, I rushed a bit. I figure it out

code goes like this:

function init(self)

math.randomseed(os.clock()*100000000000)
local randTable = {'#goFactory1', '#goFactory2', '#goFactory3', '#goFactory4', '#goFactory5', '#goFactory6', '#goFactory7', '#goFactory8', '#goFactory9', '#goFactory10' } 

local pos = go.get_position()

factory.create(randTable[math.random(#randTable)], go.set_position(pos))

end

my problem was actually go.set_position(pos), it was supposed to be only pos instead. And console didn’t show any error, that’s what confused me.

My next step will be to implement for loop,
in that for loop (4 cycles) I need to create 4 random objects in total from randTable. My confusion now is how to avoid duplicating instances, because that random function can respawn 2 or more same instances in that 4 cycles…
I am migrating from GameMaker, apologies for confusing questions, there I would solve this with if instance_exists function. I am looking in defold API and I am not finding similiar function to compare if go exists


If you store the random number in a variable…

local factoryN = math.random(#randTable)
factory.create(randTable[factoryN], pos)

… you can then remove that number from randTable to stop it from showing up again:

table.remove(randTable, factoryN)


Since table.remove() also returns the removed value, you can shorten it to just:

local factoryN = math.random(#randTable)
factory.create(table.remove(randTable, factoryN), pos)
2 Likes

Wow, awesome! Thanks for the tip!