I'm making an tower defense game but the enemies are taking random path. Is there a function that change the order for example: Apple: 0 Cheese: 0 Water: 0 To Apple: 1 Cheese: 0 Water: 0 So when i call the GetChildren function he give me apple first?
Can we set the GetChildren() order in a folder?
1 answer
You will have to sort the table of children yourself. Luckily for you, lua has a sort function for tables that allow you to use a custom sorting function: table.sort.
table.sort(t, comp)
The function's first argument is the table you want to sort, and the second is the comparison function. The comparison function has to have 2 parameters, and the function has to return true if the first parameter is supposed to be before the second.
Here's an example:
tab = {
{
["Name"] = "Second",
["Value"] = 2
},
{
["Name"] = "Third",
["Value"] = 3
},
{
["Name"] = "First",
["Value"] = 1
}
}
for k, v in pairs(tab) do
print(v.Name, v.Value)
end
-- Output:
-- Second 2
-- Third 3
-- First 1
table.sort(tab, function(first, second)
return first.Value < second.Value
end)
for k, v in pairs(tab) do
print(v.Name, v.Value)
end
-- Output:
-- First 1
-- Second 2
-- Third 3
We can apply this to your problem. One way is to have a dictionary where the names are associated with an order:
local order = {
["Apple"] = 1,
["Cheese"] = 2,
["Water"] = 3
}
table.sort(tableOfParts, function(first, second)
-- Assuming tableOfParts is a table containing parts
return order[first.Name] < order[second.Name]
end)
Another way is to add an IntValue in the NPCs, assuming you're using GetChildren on a model containing all NPCs. Name this IntValue "Order" or however you like, then make it's value its order. To be clear, you do this in studio while you're not testing.
local NPCs = workspace.NPCs:GetChildren() -- assuming workspace.NPCs contains all NPCs
table.sort(NPCs, function(first, second)
return first.Order.Value < second.Order.Value
end)
Hope this helps.
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Great answer it helped me too. Thanks!