Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to randomly assign a “bed” to multiple NPCs ?

Asked by 2 years ago

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!!!!

1 answer

Log in to vote
0
Answered by
Xapelize 2658 Moderation Voter Community Moderator
2 years ago

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
0
Incase you are confused about the logic here: Let's say I have a shopping stroller. I pick an random item in the grocery store, then take another random item in the grocery store, but before putting the item in your stroller, you check if your stroller already have that item. If there is, pick another random item. If there isn't, put the randomized item in, and repeats. Now you have a shopping str Xapelize 2658 — 2y
0
Hey! Tysm for replying! The script was really helpful Sorry for bothering again, but how could I assign each number to a bed (I'm not good with stuff like this) User#48886 0 — 2y
0
make that to a new question and add some more scripts for example @Vhexp Xapelize 2658 — 2y
Ad

Answer this question