Local Scripts
The point of local scripts is to make edits to something only a client can see. UI or local parts can only be seen by a single client, so those are edited via local scripts. If you're making changes to the game, you need to use a server sided (or normal)
How to Get Player with a Server Script
Use GetPlayerFromCharacter
. The argument is the player's character and it will return the character.
1 | local Players = game:GetService( "Players" ) |
3 | local player = Players:GetPlayerFromCharacter(Character) |
5 | print (player.Name.. " is a player." ) |
7 | print ( "Not a player..." ) |
Implementing with a Touched event
Here's how your code would look like if you combined it with GetPlayerFromCharacter
.
1 | local Part = script.Parent |
2 | Part.Touched:Connect( function (hit) |
3 | local player = game:GetService( "Players" ):GetPlayerFromCharacter(hit.Parent) |
4 | if player and script.Parent.Parent.TrafficLight 1. TSM.Red.PointLight.Brightness = = 8 then |
5 | player.leaderstats.Money.Value = player.leaderstats.Money.Value - 300 |
Debouncing
If you were to use the code as is, you'd notice that you are losing a lot more cash than just 300. The reason is because this code is being run once for every single body part and cosmetic the player is wearing. Meaning, if a player is wearing 3 hats, he could lose up to $2,700 at once! If you put a debounce, it will prevent the code from running again until a certain condition is met. In this example, the condition is time:
04 | script.Parent.Touched:Connect( function () |
Final Product
01 | local Part = script.Parent |
04 | Part.Touched:Connect( function (hit) |
05 | local player = game:GetService( "Players" ):GetPlayerFromCharacter(hit.Parent) |
06 | if not debounce and player and script.Parent.Parent.TrafficLight 1. TSM.Red.PointLight.Brightness = = 8 then |
08 | player.leaderstats.Money.Value = player.leaderstats.Money.Value - 300 |
Hope it helps!