Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I Save to DataStore in LocalScript?

Asked by 10 years ago

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

Log in to vote
1
Answered by
AxeOfMen 434 Moderation Voter
10 years ago

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
0
Thanks! That worked figgycity50 70 — 10y
Ad

Answer this question