Player character's humanoid not detecting a Touched() event after respawning

So, I have a game where you collect eggs. The code where the Touched() event happens is done on the client’s side. The humanoid touches the egg, the Touched() event fires, and the egg is discovered. After the player respawns, the code does not work. There are no errors that print in the console.

Character is defined as Player.Character or Player.CharacterAdded:Wait()

This is the code.

Character.Humanoid.Touched:Connect(function(eggPart)
	if eggPart:IsDescendantOf(EggModelsParent) then
		if not EggDebounce then
			EggDebounce = true
			local eggData = {
				egg = eggPart,
				eggClass = string.split(eggPart.Name, "_")[1];
				eggName = string.split(eggPart.Name, "_")[2];
				eggBehaviour = string.split(eggPart.Name, "_")[3]
			}
			if EggFunc_CS:InvokeServer("CheckEggOwnership", eggData) == false then
				EggFunc_CS:InvokeServer("AwardEgg", eggData)
				HUD.EggList.ScrollingFrame[eggData.eggClass .. "_" .. eggData.eggName].Collected.Visible = true
				HUD.EggCollected.EggName.Text = EggFunc_CS:InvokeServer("GetEggName", eggData)
				HUD.EggCollected.Visible = true
				task.wait(3)
				HUD.EggCollected.Visible = false
			end
			task.wait(5)
			EggDebounce = false
		end
	end
end)

Please only reply in regards to the problem that I am having.

The Touched() event isn’t being triggered anymore after respawning, because in that piece of code, ‘Character’ refers to the character model before the player had respawned. And, obviously, after a respawn, that means there is a new character model—completely different instance, meaning the ‘Character’ in that piece of code is then a nil value.

What’s the fix? Simple. Either run that piece of code inside of Player.CharacterAdded:Connect(function(character) so that it retrieves the new character every time the player respawns, or more preferably, just connect the Touched event onto the egg model. What I’d do is just make a ‘hitbox’ for the model itself and if that is touched by anything, check the parent of that part and see if it has a humanoid. If it is? It’s definitely a player’s character (unless you have NPCs in the game, that is, but it’ll be easy to distinguish a player’s character from an NPC with the method below)

It’s also much better if you do the latter on the server, and use Players:GetPlayerFromCharacter() to be able to access the player’s PlayerGui folder and enable HUD.Egglist from there.

1 Like

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