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)
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)
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)