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

Players not getting housed correctly?

Asked by 4 years ago
Edited 4 years ago

So I have this script that's supposed to give every person in the server a house. It kinda works except the last 2 players are given the same houses. Here's the script ``` local peopletohouse = game.Players:GetPlayers()

for a, b in pairs(peopletohouse) do

local homes = game.Workspace.Homes:GetChildren()

local house = homes[math.random(#homes)]

if house.Occupant.Value == "" then

house.Occupant.Value = b.Name

else

repeat

house = homes[math.random(#homes)]

until

house.Occupant.Value ~= ""

end

house.Occupant.Value = b.Name

house.Sign.SurfaceGui.TextLabel.Text = (house.Occupant.Value .. "'s Home")

print("Housed " .. b.Name .. " in " .. house.Name)

end ``` and here's the output

Housed Player1 in Home4 Housed Player2 in Home3 Housed Player3 in Home4 Housed Player4 in Home3 Housed Player5 in Home1 Housed Player6 in Home5 Housed Player7 in Home7 Housed Player8 in Home2

2 houses always end up housing 2 players. Any help?

1 answer

Log in to vote
1
Answered by
pidgey 548 Moderation Voter
4 years ago

If you could somehow automatically get a guaranteed empty house, you wouldn't need to make a loop to compare if another random house is empty. Instead get a list of homes, then for each player, remove a house from the list so it can never be chosen again.

local peopletohouse = game.Players:GetPlayers()

local homes = game.Workspace.Homes:GetChildren() --our list of homes

for a, b in pairs(peopletohouse) do
    local n = math.random(1, #homes)    --a random house from our list of homes
    local house = homes[n] --store this randomly selected house
    table.remove(homes, n) --and now remove the house from the list so it cant be chosen again!

    house.Occupant.Value = b.Name
    house.Sign.SurfaceGui.TextLabel.Text = (house.Occupant.Value .. "'s Home")

    print("Housed " .. b.Name .. " in " .. house.Name)
end
Ad

Answer this question