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

How do you access Local Player from a normal Script?

How do you access a player's "leaderstats" in a normal script, if it is possible?

game.Players.PlayerAdded:Connect(function(player)
	local leaderboard = Instance.new("Folder")
		leaderboard.Name = "leaderstats"
		leaderboard.Parent = player
	local score = Instance.new("IntValue")
		score.Name = "Cash"
		score.Parent = leaderboard
		score.Value = 100
		
end)

Like for a touch event, I want to increase the player's "Cash" when they touched the part.

local door = script.Parent
local player = game.Players.LocalPlayer
local cash = player:WaitForChild("leaderstats").Cash

door.Touched:Connect(function()
	cash.Value = cash.Value +100
end)


3 comments

0

Remote events

0

Can you elaborate on that more?

0

stop using local variables outside of their scope

2 answers

✓ Accepted answer

There is no LocalPlayer in a Script, because the Script runs on the server, which keeps track of all the connected players. So you'll always need some way to figure out which player was involved. In the case of a touch event, this is provided by the argument passed by Touched.

But the object that does the touching isn't actually the Player object where you stored the leaderstats. It's some Part (such as a left lower leg) within the Character, which is a Model associated with the player. So you'll need to get the part's Parent, then use Players:GetPlayerFromCharacter to find the Player.

There's actually a code sample on the documentation page for GetPlayerFromCharacter showing how to use it within a Touched event callback. Modifying that a little to do your change of cash, I get:

local Players = game:WaitForChild("Players")
local door = script.Parent

door.Touched:Connect(function (obj)
	local player = Players:GetPlayerFromCharacter(obj.Parent)
	-- player is nil if touched by something that's not a Player
	if not player then return end
	local score = player.leaderstats.Cash
	score.Value = score.Value + 100
end)

2 comments

0

best answer right here folks, upvote this

0

Amazing, thank you very much

Made a script that indexes the player in the players service by getting the player's name from the object that touched the door's parent. Each time they touch it, their cash value will increase by 100.

door.Touched:Connect(function(obj)
	local cash = game:GetService("Players")[obj.Parent.Name].leaderstats.Cash.Value
	cash = cash + 100
end)

2 comments

0

Did not work out, it said something is not a member of Players. Thank you for your time though

0

That error is probably from something which is not part of a player's Character touching the door, like a wall, terrain, etc.

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