Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why cant the script "get" leaderstats?

I have recently been making a game where I need a certain value to increase by another value, however, the script doesn´t work and I can´t figure out why. The output keeps telling me that leaderstats isn´t a valid child of player.

script.Parent.Touched:Connect(function(player)
	player:WaitForChild("leaderstats").Money.Value = player:WaitForChild("leaderstats").Money.Value + player:WaitForChild("leaderstats").Trash.Value
	player:WaitForChild("leaderstats").Trash.Value = 0
end)


6 comments

0

But I am doing it in a server script.

0

And it all works except from this part.

1

Posting the output as intact as possible would be of much help.

1

22:17:11.961 - Infinite yield possible on 'Workspace.Baseplate:WaitForChild("leaderstats")' 22:17:11.963 - Stack Begin 22:17:11.964 - Script 'Workspace.DumpingPart.Script', Line 2 22:17:11.965 - Stack End

1

Well that would explain it, hold on.

2 answers

✓ Accepted answer

Whoops, didn't see it soon enough.

Basically, .Touched passes on the part that you touch, so you need to figure out to who that part belongs to!

One approach is to check all the players and determine if said part is part of their character, no pun intended.


local Players=game:GetService"Players"
--NOTE: Untested.
script.Parent.Touched:Connect(function(Part)
	for k,v in pairs(Players:GetPlayers()) do --For each player..
		if v.Character then --If player has a character..
			if Part:IsDescendantOf(v.Character) then --And the part is inside of it..
				local leaderstats=player:WaitForChild("leaderstats")
				leaderstats.Money.Value = leaderstats.Money.Value + leaderstats.Trash.Value
				leaderstats.Trash.Value = 0
			end
		end
	end
end)

.Touched's parameter returns the basepart that is touching it, not the player itself. Here's an example how you would get the player:

local Player = game:GetService("Players"):GetPlayerFromCharacter(parameter.Parent)
if Player then -- check if the player exists before continuing
-- deal with leaderstats here
end

If you have any further questions, let me know & hope this solved the issue you're having ^.^

This discussion is preserved as it was. New answers, comments, and votes are closed.