Why is my function running before it is called

hello all, I have a script made for a project i’m working on, and basically i set it up so when you touch this block it fires a remote event to a local script which then moves to a module script etc. etc., but while working on it i had some problems with errors showing up, and after some rewriting i figured it out but for a while, as soon as i would start testing it would give me an error message saying i was trying to reference a nil value, which was player. I’m just wondering why the function was running before the player even touched it, or if there was a more in depth reason

finish.Touched:Connect(function(touched)
	local char = touched.Parent
	local player = game.Players:GetPlayerFromCharacter(char)
	print(player)
	local level = "One"
		finishEvent:FireClient(player,level)
end)

.Touched will fire when anything touches it, so you should just catch the event that it touches something that’s not a player. Check that touched.Parent exists then touched.Parent:FindFirstChild(“Humanoid”) to see if they are a player.

1 Like

Just a question, if you are calling this touched function in

finish.Touched:Connect(function(touched)

Why not put all this code:

local char = touched.Parent
	local player = game.Players:GetPlayerFromCharacter(char)
	print(player)
	local level = "One"
		finishEvent:FireClient(player,level)

in this touched event?

Thank you. I put that into the script just before I came here to check and it fixed it, I’m just confused and am only now wondering if it was not working because it touched the baseplate it was on? haha i think i answered the question as I was writing this. thank you again!

1 Like