The second script crashes because my guess is that it is a LocalScript. You cannot use LocalScripts for this job - it will error and stop your script.
So why doesn't it work? It's a logic error here. You are setting cash to StatisticsStorage to the key Cash - this is ALWAYS the same key and it will only be run once on one server. This is not what you want: you want to use it per-player!
01 | local DataStoreService = game:GetService( "DataStoreService" ) |
02 | game.Players.PlayerAdded:connect( |
04 | local PlayerStore = DataStoreService:GetDataStore( tostring (Player.userId), "PlayerData" ) |
05 | local Cash = PlayerStore:GetAsync( "Cash" ) |
08 | PlayerStore:SetAsync( "Cash" , Cash) |
10 | local Value = game.ReplicatedStorage:FindFirstChild( tostring (Player.userId) ,, "Cash" ) |
13 | Value = Instance.new( "NumberValue" , game.ReplicatedStorage) |
14 | Value.Name = tostring (Player.userId) .. "Cash" |
16 | Value.Changed:connect( function () |
17 | local NewValue = Value.Value |
18 | PlayerStore:SetAsync( "Cash" , Cash) |
I normally would suggest using UpdateAsync, but in cases where only one server usually writes (for instance for per-player data, like here) I'd suggest just using SetAsync.
Also, I'd like to note the difference between instances and other types. On line 2 of your local script you store a variable called "text". This text is the actual value of the text in the TextBox, NOT the property itself! This is a huge difference! Setting text to something new won't change anything to the TextBox itself as you just set the variable text to something new.
For instance, try
1 | local Name = game.Workspace.Name |
3 | print (game.Workspace.Name) |
5 | game.Workspace.Name = "Hi" |
As general rule: use a .
when you try to edit properties, and otherwise don't use that unless you are working with tables. game.Workspace denotes the roblox instance, game.Workspace.Name denotes the property, not the "shortcut" to the property. Keep this in mind.
01 | local player = game.Players.LocalPlayer |
02 | repeat wait() until game.ReplicatedStorage:FindFirstChild( tostring (player.userId).. "Cash" ) |
03 | local value = game.ReplicatedStorage [ tostring (player.userId).. "Cash" ) ] |
04 | value.Changed:connect( function () |
05 | local new = value.Value |
06 | script.Parent.Text = "Cash: " ..new |
09 | value.Value = value.Value + 1 |
Try to understand these scripts and comment if you don't understand something.