<<attempt to index nil with 'instance'>> occuring randomly

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.

You must check that the part touched is part of a player’s Character since sometimes it will not be, change it to this

local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if not debounce and plr then

also change this

to this

task.wait(0.3)

since wait will probably be obsolete in the future

1 Like

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.

2 Likes

Thank you to both of you! works as intended now! :smiley:

1 Like