So I have a script that loads if the player's money equals -1, but the data loads slower than the script. It looks like this:
LocalScript that needs to wait until the data is loaded:
local money = game.Players.LocalPlayer:WaitForChild("leaderstats").Money if money.Value == -1 then -- my script here end
Script that saves and loads data:
local DataStoreService = game:GetService('DataStoreService') local DataStore = DataStoreService:GetDataStore('CashSaveSystem') game.Players.PlayerAdded:connect(function(player) local leader = Instance.new('Folder', player) leader.Name = "leaderstats" local money = Instance.new("IntValue", leader) money.Name = "Money" money.Value = DataStore:GetAsync(player.UserId) or 250 DataStore:SetAsync(player.UserId, money.Value) money.Changed:connect(function() DataStore:SetAsync(player.UserId, money.Value) end) end) game.Players.PlayerRemoving:connect(function(player) DataStore:SetAsync(player.UserId, player.leaderstats.Money.Value) end)
I know the data storing script could be better, but for now I want to leave it as it is. My only problem is: How to make the script wait until the data is loaded?
One thing you should and can do is use pcall. Here is an example:
local success, message = pcall(function() money.Value = DataStore:GetAsync(player.UserId) or 250 end) if success then print("PlayerDataLoaded") --do stuff else player.CanSave = false -- example of the note below player:Kick("Your data loading errored please rejoin") end
Now there are many problems with your code that need addressed just so you know but I will limit myself because you said to focus on the problem at hand. Now just as a note: you will want to make it so that if success = false then the player cannot save. How pcall works: it will run the code inside the pcall and if it errors then success = false and message = the error message. the variables message and success can be what you want to call them. The nice thing about pcall is is that your game will not break if the code within fails.
Edit: I misunderstood your question. lol.
use a changed event to wait. money.Changed:Connect(function() is how you should wait for the datastore to load so that when the money changes your script will run example:
money.Changed:Connect(function() if money.Value == -1 then -- code here end end) you will want to disconnect the event after using it