can someone help me with this simple code snippet?
while true do
local customerOnScreen = nil
local toyOnScreen = nil
wait(math.random(2,5))
local ranNum = math.random(1, #NPC)
customerOnScreen = NPC[ranNum]:Clone()
customerOnScreen.Parent = script.Parent.Spawned
customerOnScreen:SetPrimaryPartCFrame(CFrame.new(StartPosition.Position, Pos1.Position))
wait(math.random(4,10))
local ranNum2 = math.random(1, #NPC)
customerOnScreen2 = NPC[ranNum]:Clone()
customerOnScreen2.Parent = script.Parent.Spawned
customerOnScreen2:SetPrimaryPartCFrame(CFrame.new(StartPosition.Position, Pos1.Position))
customerOnScreen.Humanoid:MoveTo(Pos1.Position)
customerOnScreen.Humanoid.MoveToFinished:Wait()
customerOnScreen.Humanoid:MoveTo(Pos2.Position)
customerOnScreen.Humanoid.MoveToFinished:Wait()
Im trying to spawn two npcs after each other but like that the other npc would wait for the other guy to spawn. But i want that the other npc walks even if the other guy didnt spawn yet. How would I do this?
It looks like you would benefit from creating separate threads for each NPC, you can do this by using
task.spawn()
You can use task.spawn to create new threads that do not yield the script, essentially, you can tell it to run a block of code, and it will start doing that, but continue through the script at the same time.
Something like this should work:
task.spawn(function()
while true do
-- Control NPC #1 here
end
end)
task.spawn(function()
while true do
-- Control NPC #2 here
end
end)
Spawn just means it will create a separate thread for your function. You pass in any other arguments normally. Spawn automatically executes the function.
Ex: task.spawn(func, arg, arg2)
Furthermore if you want to get deeper into it you could use coroutines. Coroutines are similar in that they are a separate thread but instead they are a bit more advanced as you can stop them, pause them (yield), etc. Without needing to constantly check like in a spawn.
break is actually a keyword but what it does is it breaks from whatever loop. This would mean it would break the while loop. If you just want to go to the next loop you’d use keyword continue to skip the rest of the code and go to the next loop.
No. What break does is it stops the loop that it’s in. This could be any loop: for loop, while loop, etc. If you want to go to the next loop use continue. I’m sure if you fiddle around with these keywords in Studio you’ll understand what I’m trying to say
You don’t actually need to include an “else” in an if-statement, they are optional, so if you are gonna leave your else statement blank, you might as well remove it all-together.