I’m currently working on a Minigame with 30 seats. Every round, 3 seats disappear. All seats are in a model called ‘Seats’ and are models themselves. They are numbered from 1 to 30 (Seat1,Seat2…,Seat30). This is the script I used to remove 3 Seats every round:
local function RemoveSeats()
local availableSeats = {}
for i,Seat in pairs(Seats:GetChildren()) do
if Seat:IsA("Model") then
table.insert(availableSeats,i,Seat)
end
end
for i = 1,3 do
local RandomNumber = math.random(1,#availableSeats)
local Seat = availableSeats[RandomNumber]
Seat:Destroy()
table.remove(availableSeats,RandomNumber)
end
end
while wait(10) do
RemoveSeats()
end
Why, however, it does not remove the destroyed seats from the table every time and this error occurs: attempt to index local 'Seat' (a nil value)
in the line where I call Seat:Destroy()
Why and is this a good way to achieve what I want?
Just adding a check to see if the object exists would solve your problems.
for i = 1,3 do
local RandomNumber = math.random(1,#availableSeats)
local Seat = availableSeats[RandomNumber]
if Seat then
Seat:Destroy()
table.remove(availableSeats,RandomNumber)
end
end
local availableSeats = {}
local loc = 0
for i,Seat in pairs(Seats:GetChildren()) do
if Seat:IsA("Model") then
availableSeats[loc] = Seat
loc = loc + 1
end
end
for i = 1,3 do
local RandomNumber = math.random(1,#availableSeats)
local Seat = availableSeats[RandomNumber]
Seat:Destroy()
table.remove(availableSeats,RandomNumber)
end
Personally, I avoid table.insert since it is more confusing to me. I added the variable loc to place each variable in the table so I know that it’s there when I want to grab from it latter. It also reduces the possibility of empty indexes.