Hello,
I am working on a data saving script and for some reason I am getting two errors. The first one being
ServerScriptService.Script:17: attempt to index nil with 'WaitForChild'
And the second one being:
Unable to cast to Array
Here is the script:
local DataStore = game:GetService("DataStoreService"):GetDataStore("ammo")
local toolname = "10mm"
local valuename = "ammo"
local value2name = "maxammo"
game.Players.PlayerAdded:Connect(function(player)
local function onCharacterAdded(character)
local backpack = player:WaitForChild("Backpack")
local tool = backpack:FindFirstChild(toolname)
local value = tool:WaitForChild(valuename)
local value2 = tool:WaitForChild(value2name)
end
player.CharacterAdded:Connect(onCharacterAdded)
local backpack = player:WaitForChild("Backpack")
local tool = backpack:FindFirstChild(toolname)
local value = tool:WaitForChild(valuename)
local value2 = tool:WaitForChild(value2name)
local data
local key = "Player_".. player.UserId
local success, errormessage = pcall(function()
data = DataStore:GetAsync(key)
end)
if success then
value.Value = data
value2.Value = data
elseif data == nil then
value.Value = 0
value2.Value = 0
else
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local key = "Player_".. player.UserId
local data1 = player.Backpack:WaitForChild("10mm"):WaitForChild("ammo").Value
local data2 = player.Backpack:WaitForChild("10mm"):WaitForChild("maxammo").Value
DataStore:SetAsync(key, data1, data2)
end)
local DataStore = game:GetService("DataStoreService"):GetDataStore("ammo")
local toolname = "10mm"
local valuename = "ammo"
local value2name = "maxammo"
game.Players.PlayerAdded:Connect(function(player)
local backpack = player:WaitForChild("Backpack")
local tool = backpack:WaitForChild(toolname)
local value = tool:WaitForChild(valuename)
local value2 = tool:WaitForChild(value2name)
local data
local key = "Player_".. player.UserId
local success, errormessage = pcall(function()
data = DataStore:GetAsync(key)
end)
if not success then
warn(key,errormessage)
return
end
if data then
value.Value = data[1]
value2.Value = data[2]
else
value.Value = 0
value2.Value = 0
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local key = "Player_".. player.UserId
local data1 = player.Backpack:WaitForChild("10mm"):WaitForChild("ammo").Value
local data2 = player.Backpack:WaitForChild("10mm"):WaitForChild("maxammo").Value
DataStore:SetAsync(key, {data1,data2})
end)
Alright, I did that and then I realized something. After looking at my old script and having a friend play test the game, it appears the ammo data saves and loads for everyone else with my old script. Doesn’t save/load for me but does for them, so weird. But thanks for your help.