Lootcrate system not working

I got a lootcrate system and am trying to make it more efficient by searching for children in a ‘Tools’ folder and giving a random tool to the player from the Tools folder. However, it returns a warning and an error. The warning is: ‘argument #1 expects a string, but Instance was passed’ and the error is: ‘Workspace.rooms.challenge room 1.crate.Script:18: attempt to index nil with ‘Clone’’

this is my code:

prox = script.Parent.Prox
script.Parent.Prox.Attachment.ProximityPrompt.PromptButtonHoldBegan:Connect(function()
	prox.Press:Play()
	prox.Cancel:Stop()
	script.Parent.Highlight.Enabled = true
end)

script.Parent.Prox.Attachment.ProximityPrompt.PromptButtonHoldEnded:Connect(function()
	prox.Press:Stop()
	prox.Cancel:Play()
	script.Parent.Highlight.Enabled = false
end)

script.Parent.Prox.Attachment.ProximityPrompt.Triggered:Connect(function(player)
	local children = game.ReplicatedStorage.Tools:GetChildren()
	local M = math.random(#children)
	print(M)
	clone = game.ReplicatedStorage.Tools:FindFirstChild(children[M]):Clone()
	clone.Parent = player.Backpack
	script.Parent.Top.Top1.Anchored = false
	script.Parent.Top.Top2.Anchored = false
	if clone ~= nil then
		script.Parent.Bottom.Part.SurfaceGui.TextLabel.Text = clone.Name
	end
	prox.Open:Play()
	prox.Cancel:Stop()
	local x = script.Parent.WorldPivot.X
	local y = script.Parent.WorldPivot.Y
	local z = script.Parent.WorldPivot.Z
	local explosion = Instance.new("Explosion")
	explosion.BlastRadius = 10
	explosion.BlastPressure = 5
	explosion.ExplosionType = Enum.ExplosionType.NoCraters
	explosion.DestroyJointRadiusPercent = 0
	explosion.Position = Vector3.new(x,y,z)
	explosion.Parent = workspace
	prox.boom:Play()
	prox.Attachment.ProximityPrompt.Enabled = false
	script.Parent.Highlight.Enabled = false
	script.Parent.Bottom.Part.Material = Enum.Material.Plastic
	script.Parent.Bottom.Part.Color = Color3.new(0.462745, 0.443137, 0.458824)
	script.Parent.Bottom.Particle.Beam.Enabled = false
	script.Parent.Top.Top1.VectorForce.Enabled = true
	wait(0.2)
	script.Parent.Top.Top1.VectorForce.Enabled = false
end)

You are using FindFirstChild which is for finding a child with a name. Instead you already have found the child with your M index. So I suggest removing this:

clone = game.ReplicatedStorage.Tools:FindFirstChild(children[M]):Clone()

and change it to:

clone = children[M]:Clone()
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.