Is this script correct?

Hi. I have done some research on leaderstats and how to use them but when i use this script;

local ls = Instance.new("Folder", plr)
	ls.Name = "leaderstats"
	
	local moneyValue = Instance.new("IntValue", ls)
	moneyValue.Name = "Money"
	moneyValue.Value = money
	while true do
		wait (5)
		moneyValue.Value = 100
	end

It errors in the output (a different client script)

The leaderstat adder works but it breaks the shop I made (and the while loop breaks)

Sources I used:
How Would I Change Leader-stat Values Using The Server? - Help and Feedback / Scripting Support - DevForum | Roblox

Loops (roblox.com)

Beginner’s Roblox Scripting Tutorial #17 - Leaderboards / leaderstats (Beginner to Pro 2019) - YouTube

Any help would be appreciated! Thanks!

The leaderstat has to be parented to the player and the number values have to be parented to the leaderstats folder.

while true do
		wait (5)
		moneyValue.Parent = ls
		moneyValue.Value = 100
	end

Oh, so the shop works without the while loop

If there is any code under this it won’t run because the thread is in an infinite while loop.

You could put the while loop in it’s own thread by doing

task.spawn(function()
   while true do
        task.wait(5)
        money.Value = 100 -- idk why you would make the value == 100 every 5 seconds, you should only update the value if the value is different than the old value
   end
end)

my whole studio crashed

1 Like

I’m assuming you put task.spawn in the while loop or didn’t put a task.wait in the while loop

That’s what happens when you don’t yield in an infinite loop

1 Like
task.spawn(function()
   while task.wait(5) do
        money.Value += 5
   end
end)

ill just do this
moneyValue.Value = moneyValue.Value +100

You can do that or do

Money.value += 100

It’s just a faster way of writing it

One more question. Can you acsess leaderstats from a local script?

Yes but don’t write to them from a local script they won’t get replicated (plus massive security flaw)

So i cant make this visible when the player gains 100 cash?

image

Of course you can, you can read leaderstats on the client just don’t write to them

Only write to leaderstats on the server.