-
I have a value in the player that is added when they join. I want to change that value when a part detects that a player has hit it.
-
I can’t access the value through the player model, because it is in the player in the “Players” folder/service/whatever you call it.
-
I’ve tried putting the value directly into the player model by using the player.Character property, but it never seems to work. I also tried looping through the players when the part is hit and change the value of the player who’s name matches the player model that hit the part.
I want to either access the player in the “Players” thing from the player model, or insert the value into the player model from the beginning.
I’m relatively new to developing, so I don’t really know how else I could go to solving this, thanks!
1 Like
In order to access the Player
instance from their Character, you can utilize a method of the Players
service called :GetPlayerFromCharacter()
. This will allow you to access the Player
and any values/folders/etc. inside of the instance.
Here’s an example:
local Players = game:GetService("Players") -- References the Players service
local part = script.Parent -- Assuming the script is directly in the part, script.Parent will refer to the part that players will step on
local function partTouched(objectThatTouchedThePart) -- Creates a function called "partTouched". When this is activated from the .Touched event, we will be able to reference the object that touched the part.
local player = Players:GetPlayerFromCharacter(objectThatTouchedThePart.Parent) -- This will check if the parent of the object that touched the part is a Character model that belongs to a player
if player then -- If it was a player's Character that touched the part, then...
local valueObject = player:FindFirstChild("NameOfValueHere") -- This will look for something inside of the player instance called "NameOfValueHere"
if valueObject then -- If the value you're storing inside of the player can be found, then...
valueObject.Value += 100 -- You can reference its "Value" property and change it accordingly
end -- Ends the "if valueObject then" statement
end -- Ends the "if player then" statement
end -- Ends the partTouched function
part.Touched:Connect(partTouched) -- Whenever the part is touched by anything, it'll activate the function called "partTouched"
3 Likes
I just realized that I’ve seen this in scripts before, but It just went over my head. Thanks for your help! 
1 Like
No problemo! If you need additional information, make sure to utilize the Roblox Developer Hub, as the API Reference can be found there which explains lots of different things in more detail 
For instance, GetPlayerFromCharacter
is documented there along with all other methods of the Players service.
1 Like