I've been trying to change the value of a stat "level" when a brick is touched. I have a LocalScript in the brick with this code:
1 | function OnTouched(Part) |
2 | local level |
3 | print ( "Touched" ) |
4 | level.Value = level.Value + 1 |
5 | end |
6 |
7 | script.Parent.Touched:Connect(OnTouched) |
And this is the code for the leaderboard:
01 | local function onPlayerJoin(player) |
02 | print ( "Joined" ) |
03 | local leaderstats = Instance.new( "Folder" ) |
04 | leaderstats.Name = "leaderstats" |
05 | leaderstats.Parent = player |
06 |
07 | local jumps = Instance.new( "IntValue" ) |
08 | jumps.Name = "Jumps" |
09 | jumps.Value = 0 |
10 | jumps.Parent = leaderstats |
11 |
12 | local level = Instance.new( "IntValue" ) |
13 | level.Name = "Level" |
14 | level.Value = 0 |
15 | level.Parent = leaderstats |
Now -- Why doesn't the LocalScript in the brick work at all? I assumed that it was a problem with just level.Value = level.Value + 1
. But when I put the print ("Touched")
into the script, it never displayed it into the console.
The reason this isn't working is because local scripts cannot run in the workspace. They can only run somewhere that is a direct descendant of the player, i.e. StarterPack
, StarterGui
, or StarterPlayerScripts
. The only exception is in the client's character, which is typically achieved by placing the local script in StarterCharacterScripts
. To fix this, just put this code in a server script instead of a local script:
01 | function OnTouched(Part) |
02 | local player = game.Players:GetPlayerFromCharacter(Part.Parent) |
03 | if player then |
04 | local leaderstats = player:FindFirstChild( "leaderstats" ) |
05 | if leaderstats then |
06 | leaderstats.Level.Value = leaderstats.Level.Value + 1 |
07 | end |
08 | end |
09 | end |
10 |
11 | script.Parent.Touched:Connect(OnTouched) |
You didn't set "level" to anything and LocalScripts don't run in anything that isn't a descendant of your player. Put it in a regular Script.
01 | local waittime = 3 |
02 | local debounce = true |
03 | -- This debounce variable prevents the script from spamming points |
04 |
05 | function OnTouched(hit) |
06 | if hit and hit.Parent and debounce then |
07 | -- Make sure hit is isn't nil and debounce is ready |
08 | debounce = false |
09 | local player = game.Players:GetPlayerFromCharacter(hit.Parent) |
10 | -- Get the player from whatever bodypart hit the brick. |
11 | if player then |
12 | -- Make sure a player hit the brick |
13 | local leaderstats = player:FindFirstChild( "leaderstats" ) |
14 | -- Make sure they have the leaderstats Value. |
15 | local level = leaderstats and leaderstats:FindFirstChild( "level" ) |
I'm not too sure about this, but you didnt set anything for level's variable, meaning that the game doesn't know what level is. Something you CAN do however is change it to:
1 | local level = leaderstays:FindFirstChild( "level" ) |
Also, local scripts only work in startergui, starterplayer, and starterpack.