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

How do I Save to DataStore in LocalScript?

In my tool, there's a LocalScript that operates the tool and fires my laser gun. When a humanoid is killed by the gun (when a LocalScript only event (click) runs), I add 1 to the player's kills, and level them up if they hit 10 kills. But because DataStore only runs on server Scripts, it errors and the gun will no longer shoot. How do I save the data?

 --do damage to any humanoids hit
        local humanoid = hit and hit.Parent and hit.Parent:FindFirstChild("Humanoid")
        if humanoid then
            humanoid:TakeDamage(45)
			if humanoid.Health == 0 then
				--add a kill
				local DataStore = game:GetService("DataStoreService"):GetDataStore(user.Name)
--[[errors here]]	DataStore:IncrementAsync("kills", 1)
				kills = DataStore:GetAsync("kills")
				if kills == 10 then
					DataStore:IncrementAsync("gun", 1)
					DataStore:SetAsync("kills", 0)
					user.Humanoid.Health = 0
				end
			end
        end
		end)

1 answer

✓ Accepted answer

Use RemoteFunctions to convey information from the client to the server where you can then store the data you want in the DataStore

On the server:

local gunTransaction = Instance.new("RemoteFunction")
gunTransaction.Name = "GunTransaction"
gunTransaction.OnServerInvoke = function(player)
	--the player argument is supplied by ROBLOX and will always be the player that called this function from localscript
	--add your logic here for retrieving and storing kills/levels in DataStore
end
gunTransaction.Parent = workspace

On the client:

--...
--Your other setup code here
--...

local gunTransaction= workspace:WaitForChild("GunTransaction")
local humanoid = hit and hit.Parent and hit.Parent:FindFirstChild("Humanoid")
if humanoid then
	humanoid:TakeDamage(45)
	if humanoid.Health <= 0 then
		--add a kill
		gunTransaction:InvokeServer(player)
	end
end

1 comment

0

Thanks! That worked

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