How could I assign a random bed to multiple NPCs at the same time without them ending up using the same bed? Help is appreciated since I cannot finish the night cycle without this, therefore can't continue the game development.
Simple explanation: A player creates a town, new villagers (NPCs) want to live in the town. The player places multiple beds, and once It's nighttime villagers need to go to a random bed without ending up on the same bed. Similar way to Minecraft villagers
I've tried using math.random()
on a table but they ended up on the same bed.
Thanks!!!!
Put the math.random()
result into a list. If you find the same result inside the list when you generate a new math.random()
value, keep choosing a new bed until you get a bed that is not occupied.
Example:
local List = {} local Index1 = math.random(1, 3) local Index2 -- Placeholder local Index3 -- Placeholder -- Put the Index1 result into the List table.insert(List, Index1) -- Repeat until Index2 have a unique number that doesn't exist on List repeat Index2 = math.random(1, 3) until not table.find(List, Index2) -- Put the Index2 result into the List table.insert(List, Index2) -- Repeat until Index3 have a unique number that doesn't exist on List repeat Index3 = math.random(1, 3) until not table.find(List, Index3) print(Index1, Index2, Index3) -- Run this code a few times, and you can see they are all randomized but never repeats