Part that remove player tool from backpack with percentual

I want a script that has a percentage that removes an object from the player’s inventory when it passes through it I have the code but it doesn’t work can you help me here is the code

local ItemName = “NomeOggetto”
local Chance = 0.25

script.Parent.Touched:Connect(function(part)
if part.Parent and part.Parent:FindFirstChildOfClass(“Humanoid”) then
local player = game.Players:GetPlayerFromCharacter(part.Parent)
if player then
if math.random() <= Chance then
local backpack = player:FindFirstChildOfClass(“Backpack”)
if backpack and backpack:FindFirstChild(ItemName) then
backpack[ItemName]:Destroy()
end
end
end
end
end)

The script doesnt work because math.random() can only choose numbers without decimals.

local ItemName = "NomeOggetto"
local Chance = 0.25

script.Parent.Touched:Connect(function(part)
	if part.Parent and part.Parent:FindFirstChildOfClass("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(part.Parent)
		if player then
			if (math.random(1, 100) / 100) <= Chance then
				local backpack = player:FindFirstChild("Backpack")
				if backpack and backpack:FindFirstChild(ItemName) then
					backpack[ItemName]:Destroy()
				end
			end
		end
	end
end)

@CZXPEK If you take a look at math.random you’ll see that when called without any arguments, it will by default return a number between 0 and 1

The script actually doesn’t work because you’re only checking the player’s backpack for the tool, if the player has the tool equipped then it would simply not find the tool in the backpack. To solve this just check if the tool exists inside the player’s character and destroy it if it does.

local ItemName = "NomeOggetto"
local Chance = 0.25

script.Parent.Touched:Connect(function(part)
	if part.Parent and part.Parent:FindFirstChildOfClass("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(part.Parent)
		if player then
			if math.random() <= Chance then
				local backpack = player:FindFirstChildOfClass("Backpack")
				if backpack and backpack:FindFirstChild(ItemName) then -- Check in backpack
					backpack[ItemName]:Destroy()
				else if part.Parent:FindFirstChild(ItemName) then -- Check in character
						part.Parent[ItemName]:Destroy()
					end
				end
			end
		end
	end
end)

1 Like

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