Code works on the first time only

local message = Instance.new("Message")

script.Parent.Touched:connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.parent)
local cashmoney = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
message.Parent = game.Workspace
message.Text = player.Name.." won the quarter mile drag race!"
if cashmoney then
cashmoney.Value = cashmoney.Value + 1	
end
wait(2)
script.Parent.CanCollide = true
wait(8)
message:Destroy()
wait(30)
script.Parent.CanCollide = false
end)

When the player tries to go again for a second time the script does not work at all. Is there a way I can fix this issue if so how? And keep in mind that it only works the first time only.
87d2bf673e8fc8d4594eac0af2149016

1 Like

Please refrain from using Message, it has now been deprecated and not suitable for use. You can make your own custom GUI now.

Are you sure this is the whole script? It doesn’t look like the error comes from line 8.

There are a few different issues with the code provided:

  1. There are no checks performed to assure the player that touched the parts exists. For example, if another part in-game touched the winning part then it would result in the error you’ve provided because the “player” variable is nothing.

  2. Once the message is destroyed, it cannot be reparented. Instead. you should be creating the message instance within the function.


Fixed code

I’ve also added in a debounce to prevent players from winning multiple times when the touch event fires multiple times as they walk on the part. It works by:

  1. Checking if the winDebounce is false every time
  2. If a player is found to have touched the part, then it will set the winDebounce to true
  3. At the end of the code when the part is made collideable again, winDebounce is set back to false
local winDebounce = false


script.Parent.Touched:Connect(function(hit)
	
	if winDebounce == false then
	
		local player = game:GetService('Players'):GetPlayerFromCharacter(hit.Parent)
		
		if player then

			winDebounce = true

			local message = Instance.new('Message')
			local cashmoney = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
			
			message.Text = player.Name..' won the quarter mile drag race!'
			message.Parent = workspace
		
			if cashmoney then
				cashmoney.Value = cashmoney.Value + 1	
			end
			
			wait(2)
			
			script.Parent.CanCollide = true
			
			wait(8)
			
			message:Destroy()
			
			wait(30)
			
			winDebounce = false
			script.Parent.CanCollide = false
		
		end
		
	end
	
end)
2 Likes

Works thank you for the help! I’m still new to scripting and I have never used Debounce before in any of my scripts and I have learned something new today.

1 Like

Glad I was able to help!

If you’re more interested in learning about debounce systems, then the Developer Hub has a more in-depth article on it you can read up on: