Hello! I am making a Roblox game with a food ordering system similar to Welcome to Bloxburg. I have created a line where NPCs wait until the cashier can take their order. I want to implement a system using indexing where when the NPC reaches the front of the line, a function will fire, and there will be a request for what the NPC wants to order. The problem is I am using a while loop, and I don’t know how to index the NPC in the front of the line without constantly firing the event over and over again. I had an idea of firing the table every time the NPC in the front of the line changed, but I don’t know how I would do this. Are there any approaches that I can take to complete my goals? Thank you.
Script:
-- services
local ServerStorage = game:GetService("ServerStorage")
-- folders
local npcs = ServerStorage:WaitForChild("NPCS")
local npcsChildren = npcs:GetChildren()
local lineParts = workspace:WaitForChild("LineParts")
local linePartsChildren = lineParts:GetChildren()
local lastNpc = tick()
local npcWaitTime = 5
local customerLine = {}
-- functions
function randomNpc()
local randomNpc = math.random(1, #npcsChildren)
local chosenNpc = npcsChildren[randomNpc]:Clone()
chosenNpc.Parent = workspace
return chosenNpc
end
function findIndexInLine(chosenNpc)
local indexInLine = table.find(customerLine, chosenNpc)
return indexInLine
end
function moveNPC(chosenNpc)
local positionInLine = findIndexInLine(chosenNpc)
local chosenLinePart = linePartsChildren[positionInLine]
chosenNpc.Humanoid:MoveTo(chosenLinePart.Position)
end
function spawnNPC()
local newNpc = randomNpc()
table.insert(customerLine, newNpc)
moveNPC(newNpc)
end
while wait() do
for i = #customerLine, 1, -1 do
local customer = customerLine[i]
if customer == nil or customer.Parent == nil or customer.Humanoid.Health <= 0 then
table.remove(customerLine, i)
end
end
for i, npc in pairs(customerLine) do
moveNPC(npc)
end
if #customerLine < #linePartsChildren and tick() - lastNpc >= npcWaitTime then
lastNpc = tick()
spawnNPC()
end
end