Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Get a random child with a specific name?

Edit: i added the full script

i've been trying to get this script to select a random child with a specific name like "9mm"

rEvent4.OnServerEvent:Connect(function(plr)
	if ammo.Value < 15 then
			local backpack = plr.Backpack:GetChildren()
			local all9mm = {}
			
			for i, v in ipairs(backpack) do
				if v.Name == "9mm" then
					table.insert(all9mm, v)
				end
			end
			
			local chosenitem = all9mm[math.random(1, #all9mm)]
			print(chosenitem.Name)
		end
	end)

1 answer

✓ Accepted answer

If I understand what you're trying to do correctly, you could add all children with the name "9mm" to a separate table, then choose a random value from that table

local backpack = plr.Backpack:GetChildren()
local all9mm = {}
for i,v in ipairs(backpack) do
	if v.Name == "9mm" then
		table.insert(all9mm, v)	
	end
end
local chosenitem = all9mm[math.random(1, #all9mm)]
print(chosenitem)

6 comments

0

it works thank you!

0

ok wait i have a problem

0

the script prints out 2 or more random items when its just supposed to be 1 random item

0

make sure the last two lines are outside of the for loop so that they only happen one time

0

i did but it still happens

0

ok it worked, just had to put a if not debounce function between them

This discussion is preserved as it was. New answers, comments, and votes are closed.