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

Help with fixing my leaderstats reset on death script?

I am making a survival game and I have a script that resets the players leaderstat on player death but it resets all leaderstats instead of just my time leaderstat called "Timex" here is my script:

local function onPlayerAdded(plr)
    local con1
    plr.CharacterAdded:Connect(function(char)
        repeat wait() until char.Parent and char:FindFirstChild("Humanoid")
        con1 = char.Humanoid.Died:Connect(function()
            for i, v in pairs(plr.leaderstats:GetChildren()) do
                if tostring(v.ClassName):find("Value") then
                    v.Value = 0
                end
            end
        end)
        repeat wait() until not char.Parent
        con1:Disconnect()
    end)
end

game.Players.PlayerAdded:Connect(onPlayerAdded)

Thanks.

1 answer

✓ Accepted answer

Firstly, you do not need to store the humanoid died connection in a variable because all connections tied to an instance are automatically disconnected as soon as the instance is destroyed.

Secondly, the "ClassName" property of any instance is already a string, making it useless to convert it again to string.

Thirdly, your code assumes that any instance with the word "Value" in it's "ClassName" property is an int value or number value which isn't the case for the other instances that has the word "Value" in its "ClassName" property. (E.g "BoolValue", "StringValue", "Vector3Value", "ObjectValue", etc)

Lastly, you only need to check if the "Name" property of each object is "Timex" since you stated that you only want to reset your time leaderstat called "Timez"

That being said, lets fix your code:

local function onPlayerAdded(plr)

	plr.CharacterAdded:Connect(function(char)
		repeat task.wait() until char.Parent and char:FindFirstChild("Humanoid")
		 char.Humanoid.Died:Connect(function()
			for i, v in pairs(plr.leaderstats:GetChildren()) do
				if v.Name == "Timex" then
					v.Value = 0
					break
				end
			end
		end)
		repeat task.wait() until not char.Parent
		
	end)
end

game.Players.PlayerAdded:Connect(onPlayerAdded)

Hope I helped!

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