Coin collection not working

Hello! I am currently trying to make a racing game and I want the player to be able to collect coins along the track. However, sometimes the coins won’t respawn and I will get this error:
Workspace.Coins.Respawning Coin.CollectionScript:8: attempt to index nil with ‘WaitForChild’
Here is my code on a server script:

local debounce = true

script.Parent.Hitbox.Touched:Connect(function(hit)
		if debounce == true then
			debounce = false
			script.Parent.Transparency = 1
			local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
			local leaderstats = Player:WaitForChild("leaderstats")
			local Coins = leaderstats:WaitForChild("Coins")
			Coins.Value = Coins.Value + 1
			script.Parent.CollectionSound:Play()
			script.Parent.Transparency = 1
			task.wait(1)
			debounce = true
			script.Parent.Transparency = 0
	end	
end)

If you think you know what went wrong, please let me know. Have a wonderful day!

This could possibly be caused by a part that is not a child of the players character being detected by the Hitbox. Not so sure about it though considering your :GetPlayerFromCharacter probably would’ve errored. But im not sure about it.

Yes, you can check through this method:

if game.Players:GetPlayerFromCharacter(hit.Parent) then — returns the player when touched by their character, and nil when touched by anything else
    —your code
end

the :GetPlayerFromCharacter() function only looks for player instances, so if there isnt one, it returns nil

1 Like

It worked! Thank you so much! Have a good day!

1 Like

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