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

(FilteringEnabled) How to make this Touched script add a higher value to a player's stats?

I am making a script that makes the player gain more XP, Fullness, and Health when they touch a berry, however it only skips to saying "Berry already touched" and does nothing. (FIlteringEnabled is on) Here is the script I am using:

--ServerScript
local HitAlready = false
script.Parent.Touched:connect(function(hit)
if not HitAlready then
HitAlready = true
local Player=game.Players:GetPlayerFromCharacter(hit.Parent)
if Player==nil then return end
Player.Stats.Fullness.Value = Player.Stats.Fullness.Value + script.Parent.Hunger.Value 
Player.Stats.XP.Value = Player.Stats.XP.Value + script.Parent.XP.Value
Player.Stats.Health.Value = Player.Stats.Health.Value + script.Parent.Health.Value 
script.Parent:Destroy()
else
	print("Berry already touched")
end
end)

1 comment

0

You should try to indent your code to make it more easier for others to read.

1 answer

✓ Accepted answer

The problem might be that the berry is touching something other than a player's character (such as the ground), which causes the script to execute HitAlready = true, even though this should not happen. To fix this you could change your code to

--ServerScript
local HitAlready = false
script.Parent.Touched:connect(function(hit)
    local Player=game.Players:GetPlayerFromCharacter(hit.Parent)
    if Player==nil then
        return
    end
    if not HitAlready then
        HitAlready = true
        Player.Stats.Fullness.Value = Player.Stats.Fullness.Value + script.Parent.Hunger.Value 
        Player.Stats.XP.Value = Player.Stats.XP.Value + script.Parent.XP.Value
        Player.Stats.Health.Value = Player.Stats.Health.Value + script.Parent.Health.Value 
        script.Parent:Destroy()
    else
        print("Berry already touched")
    end
end)

Since you are making the call script.Parent:Destroy(), you don't even need HitAlready; the touch connection will automatically disconnect after the berry is destroyed, so players can't hit it again. Hence, your code can be simplified to

--ServerScript
script.Parent.Touched:connect(function(hit)
    local Player=game.Players:GetPlayerFromCharacter(hit.Parent)
    if Player==nil then
        return
    end
    Player.Stats.Fullness.Value = Player.Stats.Fullness.Value + script.Parent.Hunger.Value 
    Player.Stats.XP.Value = Player.Stats.XP.Value + script.Parent.XP.Value
    Player.Stats.Health.Value = Player.Stats.Health.Value + script.Parent.Health.Value 
    script.Parent:Destroy()
end)

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