Improving the code

Hello

I have this code that I feel could be improved so I can easily work with it
Is there any way to improve it so that it looks like other regular leaderstat code
I am trying to do a datastore on my own
Thanks in advance

local Players = game:GetService"Players"

Players.PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function(Character)
		local LeaderStats = Instance.new("Folder", Player)
		LeaderStats.Name = "leaderstats"
		local HeadSize = Instance.new("NumberValue", LeaderStats)
		HeadSize.Value = Character.Head.Size.Magnitude
		
		local Value = Instance.new("NumberValue")
		
		Value:GetPropertyChangedSignal"Value":Connect(function(Property)
			HeadSize.Value = Character.Head.Size.Magnitude
		end)
		
		spawn(function()
			while true do task.wait()
				Value.Value = Character.Head.Size.Magnitude
			end
		end)
	end)
end)

Your using the parent parameter for instance.new

Also the way your defining Players is quite odd to me. (I highly HIGHLY suggest you use this () unless your trying to obfuscate it, which still isn’t a good idea and you use it for instance.new() aswell)

I think task.spawn is better than spawn (not sure, but it’s that way for wait())

I’d suggest changing the “Value” variable name to something better so it’s easier to read aswell

Other than that, it looks good

3 Likes

Replace while true do task.wait() with

while task.wait() do --remove the task.wait() after

or use

game:GetService("RunService").Stepped ----instead of task.wait()

then use Coroutines instead of task.spawn()

Yeah, I was wondering about that too, I will change it

I get errors (dont ask me how), will it work with brackets?

Thanks

Thank you for the help

Could I add a PlayerRemoved event in there somewhere, or will it break?

1 Like

I don’t think it it will
(3000000 char)

1 Like

Instead of this, Value:GetPropertyChangedSignal"Value":Connect you can just write Value.Changed:Connect and it will work the same.
Also, its better to use task.spawn() instead of spawn()

I don’t understand why there is a need for two values ("HeadSize and “Value”). At all given times, I believe these two will be the same. This should work fine:

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function(Character)
		local LeaderStats = Instance.new("Folder", Player)
		LeaderStats.Name = "leaderstats"
 		HeadSize = Instance.new("NumberValue", LeaderStats)
		
		task.spawn(function()
			while task.wait() do 
				HeadSize.Value = Character.Head.Size.Magnitude
			end
		end)
	end)
end)

If you think that two values are required then that’s also fine.

Yes, you can add a Player removed function after the PlayerAdded one.

Players.PlayerAdded:Connect(function(Player)
	-- stuff
end)
Players.PlayerRemoving:Connect(function(player)
	-- other stuff
end)
1 Like