Help with this error

Hello, so I’m trying to make a random tool spawner but I keep on getting this error: invalid argument #2 to ‘remove’ (number expected, got Instance) is there a way to fix this?
Here is my script:

local spawns = workspace.ToolSpawns:GetChildren()

local spawnsTable = {}

for i, v in pairs(spawns) do
	if v then
		table.insert(spawnsTable, v)
	end
end

print(#spawnsTable)

for i, v in pairs(game.ReplicatedStorage.Tools:GetChildren()) do
	if v then
		local chosenSpawn = spawnsTable[math.random(1, #spawnsTable)]
		print(chosenSpawn)
		v:Clone()
		v.Parent = workspace
		local spawnn = workspace.ToolSpawns:FindFirstChild(chosenSpawn.Name)
		v.Handle.CFrame = spawnn.CFrame
		wait(.1)
		table.remove(spawnsTable, chosenSpawn)
		chosenSpawn:Destroy()
	end
end

Thank you!

1 Like

chosenSpawn is an Instance. It needs to be a Number.

Not too sure what this is, but perhaps you want a .Value or something?

1 Like

It’s clear in the error message that the argument #2 is an instance. What are you trying to do?

1 Like

I want to make a script that spawns some tools in a CFrame of some parts in the workspace I have 3 parts in a folder and I want to choose a random one each time but never the same part that’s why I used table.remove.

I think I see the issue here, thats supposed to be an index. Try finding what math.random returns, and put that inside table.remove, thats what it needs. Since when you just put chosenSpawn, thats actually an Instance. So heres the code, simply you just add chosenSpawnNumber. No other code needs to be changed except that table.remove line.

--Replace the inside of the for loop with this.
local chosenSpawnNumber = math.random(1, #spawnsTable)
local chosenSpawn = spawnsTable[chosenSpawnNumber]
		print(chosenSpawn)
		v:Clone()
		v.Parent = workspace
		local spawnn = workspace.ToolSpawns:FindFirstChild(chosenSpawn.Name)
		v.Handle.CFrame = spawnn.CFrame
		wait(.1)
		table.remove(spawnsTable, chosenSpawnNumber)
		chosenSpawn:Destroy()
1 Like

change the table.remove line to

for i,v in pairs(spawnsTable) do
    if v == chosenSpawn then
        table.remove(spawnsTable, i)
        break
    end
end
2 Likes

you need to get the index of the chosen Spawn inside the table in your case I would just do

function ToIndex(Table, Value)
	for index, value in pairs(Table) do
		if value == Value then
			return index
		end
	end
	return false
end
table.remove(spawnsTable, ToIndex(spawnsTable, chosenSpawn))

Edit: I realised you can also do

table.remove(spawnsTable, table.find(spawnsTable, chosenSpawn))

cause table.find returns the index of the value

1 Like