Give Random Weapon On Part Touched

Hello! I have been working on a game for a while and need help with a OnTouched event script. Basically, what its supposed to do is on a specific part touched, it gets a random tool from a folder in ServerStorage and puts it into the players backpack. I searched for a while and couldn’t find anything to help me. Thanks!

2 Likes

I suggest to use a ModuleScript to have a precise Table of all your weapons like damage, cost, ammo and name

or you can just create a table
Local Guns = {Workspace.Glock,Workspace.Axe}

and on touch event
RNG = math.random(1,table.getn(Guns))

Guns[RNG].Parent = player.backpack

Also don’t forget to make a debounce*

1 Like

There might be a better way to do it, but this seems to work as well :stuck_out_tongue:

local players = game:GetService("Players")
local serverStorage = game:GetService("ServerStorage")
local weaponFolder = serverStorage:WaitForChild("FOLDERNAME") -- Change this to the name of your folder

local tools = {}
for _,v in pairs(weaponFolder:GetChildren()) do
table.insert(tools, v)
end

script.Parent.Touched:Connect(function(hit)
local plr = players:GetPlayerFromCharacter(hit.Parent)
if plr then
local randomWeapon = math.random(1, #tools)
tools[randomWeapon]:Clone().Parent = plr.Backpack
end
end)

You might want to add an if statement to check whether or not the player already has the weapon
or add a debounce that functions as a cooldown before you can get another weapon by touching the part

2 Likes

Why not just do local tools = weaponFolder:GetChildren() ?

1 Like

That’s indeed a better way to do it. Thank you for your addition! :+1: