I’m trying to make a simulator, and everything is going as planned but for this little thing:
This error is occurring randomly because as you can see the script worked 9 times before the error.
Here’s the script:
local sellPart = script.Parent
local debounce = false
sellPart.Touched:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if not debounce then
debounce = true
print("Sellpart Touched")
plr.leaderstats["Coins💵"].Value += plr.backpack.backpackStorage.Value
plr.backpack.backpackStorage.Value = 0
wait(0.3)
debounce = false
end
end)
Note: The ‘backpack’ in ‘plr’ is not Roblox’s ‘Backpack’, it’s a Folder. I also used a debounce because the player would be able to touch the part multiple times at once.
After this error, I’m not able to sell anymore.
Also,
because the player would be able to touch the part multiple times at once
Is there a way to fix this without a debounce? because the debounce doesn’t always work as intended (For example, the player can touch the part 3 times at once), which doesn’t seem to cause problems, but it’s annoying to see.
As the above post suggested, you weren’t checking if the part which caused the part touched event to fire belonged to a player, as such any part which caused the part touched event to fire would result in the parts parent being passed as an argument to the “GetPlayerFromCharacter()” function call even if the parts parent was not a character.
local sellPart = script.Parent
local debounce = false
sellPart.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then --check if player cause part touched event to fire
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if not debounce then
debounce = true
print("Sellpart Touched")
plr.leaderstats["Coins💵"].Value += plr.backpack.backpackStorage.Value
plr.backpack.backpackStorage.Value = 0
wait(0.3)
debounce = false
end
end
end)
The above modification ensures the parts parent belongs to a player before attempting to execute any further code.