Nil when fetching player from character

  1. What do I want to achieve?

I want the part to give 1 coin when touched

  1. What is the issue?

Workspace.testpart.Script:8: attempt to index nil with 'Name' - Server - Script:8

  1. What solutions have you tried so far?

Talked to the roblox unofficial discord and they couldn’t find a fix…

local player = game:GetService("Players")
script.Parent.Touched:Connect(function(touch)
	if touch:IsA("Part") then
		local plr = player:GetPlayerFromCharacter(touch)
		if plr == nil then
			print("Player is nil")
		end
		print(plr.Name)
		local coins = plr:FindFirstChild("leaderstats").Coins
		coins.Value = coins.Value + 1
	end
end)

Thanks to the ones that take time out of there day to help, Your amazing!

GetPlayerFromCharacter expects the character model, not a part from the model. Try player:GetPlayerFromCharacter(touch:FindFirstAncestorOfClass("Model"))

touch.Parent will be the character you’re looking for, as Touched only detects parts inside the character
You can do something like this:

local player = game:GetService("Players")
script.Parent.Touched:Connect(function(touch)
	if touch:IsA("BasePart") then -- r15 characters contains meshParts (~= parts) so you need to detect them as well
		local plr = player:GetPlayerFromCharacter(touch.Parent)
		if plr == nil then
			print("Player is nil")
return -- stop code from running if player is nil
		end
		print(plr.Name)
		local coins = plr:FindFirstChild("leaderstats").Coins
		coins.Value = coins.Value + 1
	end
end)

What does all this line even do though?

Thank you so much! your amazing

1 Like

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