Unable to cast value to Object (DataStore)

DataStore not Datastoring

Im pretty new to datastores so sorry if the issue is glaringly obvious lol. Ive been looking over the documentation/Yt videos to understand it better.

Anyways I have a pretty basic store here to save 3 leaderstats and when I run it It returns “Unable to cast value to object” for lines 18 and 27, the GetAsync ones. Again, pretty new to datastores so not 100% whats wrong. Ive done checks to make sure I referenced the actual stats correct and I did so its not that.

local ds = game:GetService("DataStoreService"):GetDataStore("SaveName")

game.Players.PlayerAdded:Connect(function(plr)
	wait()
	local key = "user_"..plr.UserId
	
	local SaveValue1 = plr.leaderstats.Kills
	local SaveValue2 = plr.leaderstats["NPC Kills"]
	local SaveValue3 = plr.leaderstats.Rebirths
	
	local GetSaved = ds:GetAsync(key)
	if GetSaved then
		SaveValue1.Value = GetSaved[1]
		SaveValue2.Value = GetSaved[2]
		SaveValue3.Value = GetSaved[3]
	else
		local valuesForSaving = {SaveValue1.Value, SaveValue2.Value, SaveValue3.Value}
		ds:GetAsync(key, valuesForSaving)
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local SaveValue1 = plr.leaderstats.Kills
	local SaveValue2 = plr.leaderstats["NPC Kills"]
	local SaveValue3 = plr.leaderstats.Rebirths
	
	ds:GetAsync("user_"..plr.UserId, {SaveValue1.Value, SaveValue2.Value, SaveValue3.Value})
end)

Anyways yeah, not 100% sure why im getting that error.
(also my first dev forum post so oopsies if I made a mistake in posting)

1 Like

Ah I see the problem
You’re using ds:GetAsync in the player removing function instead of ds:SetAsync, change that.
Also if player doesn’t have data when they joined then don’t use ds:GetAsync(), supply default values for each of the save value objects

For supplying default values, do smth like this

else
  SaveValue1.Value = 0
  SaveValue2.Value = 0
  SaveValue3.Value = 0
end

Yup that was it. Thanks a lot. Makes more sense now lol.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.