How to use math.random

Hello! Recently, I’ve been trying to get two random attachments from the players character, but the script does not work. It sends an error, saying “attempting to get the length of an instance”

while wait(0.5) do
	for i,v in pairs(Character:GetDescendants()) do
		if v:IsA("Attachment") then
			local RandomAttachment = v[math.random(2, #v)]
			print(RandomAttachment.Name)
		end
	end
end

How would I fix this issue? Thanks.

v is already an attachment and it is not a table. What exactly are you attempting with the attachments?

Basically, after I get the two random attachments I would create a beam between them if they’re not on the same part, it won’t really make sense without context but that’s essentially what I’m trying to do.

Have you thought of any solutions?

You should put this on the outside because you’re basically using math.random twice.

You could do something like this maybe

local Attachments = {}

while wait(0.5) do
	-- store all attachments in table
	for i, v in pairs(Character:GetDescendants()) do
		if v:IsA("Attachment") then
			table.insert(Attachments, v)
		end
	end
	
	-- get 2 random attachments from Attachments table (without duplicates)
	local A1 = table.remove(Attachments, math.random(#Attachments))
	local A2 = table.remove(Attachments, math.random(#Attachments))
	print(A1.Name, A2.Name)
	
	-- empty table
	for i in pairs(Attachments) do
		Attachments[i] = nil
	end
end
1 Like