Datastore Unable to cast value to Object

I made a script where you it should save the presents, but its working but giving a error “Unable to cast value to Object” sometimes:

local DS = game:GetService("DataStoreService"):GetDataStore("PresentsDataStoreFRFR5")
game.Players.PlayerAdded:Connect(function(plr)
	wait()
	local plrkey = "id_"..plr.userId
	local savevalue = plr.PresentsStat.Presents
	local savevalue2 = plr.PresentsStat.Present1
	local savevalue3 = plr.PresentsStat.Present2
	local savevalue4 = plr.PresentsStat.Present3
	local savevalue5 = plr.PresentsStat.Present4
	local savevalue6 = plr.PresentsStat.Present5
	local savevalue7 = plr.PresentsStat.Present6
	local savevalue8 = plr.PresentsStat.Present7
	local savevalue9 = plr.PresentsStat.Present8

	
	local GetSaved = DS:GetAsync(plrkey)
	if GetSaved then
		savevalue.Value = GetSaved[1]
		savevalue2.Value = GetSaved[2]
		savevalue3.Value = GetSaved[3]
		savevalue4.Value = GetSaved[4]
		savevalue5.Value = GetSaved[5]
		savevalue6.Value = GetSaved[6]
		savevalue7.Value = GetSaved[7]
		savevalue8.Value = GetSaved[8]
		savevalue9.Value = GetSaved[9]
	else
		local NumberForSaving = {savevalue.Value,savevalue2.Value,savevalue3.Value,savevalue4.Value,savevalue5.Value,savevalue6.Value,savevalue7.Value,savevalue8.Value,savevalue9.Value}
		DS:GetAsync(plrkey,NumberForSaving)
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	DS:SetAsync("id_"..plr.userId,{plr.PresentsStat.Presents.Value,plr.PresentsStat.Present1.Value,plr.PresentsStat.Present2.Value,plr.PresentsStat.Present3.Value,plr.PresentsStat.Present4.Value,plr.PresentsStat.Present5.Value,plr.PresentsStat.Present6.Value,plr.PresentsStat.Present7.Value,plr.PresentsStat.Present8.Value})
end)

How do i fix this error?

1 Like

line 29 should be using :SetAsync if youre trying to change the data

also you should put the values into a table so you dont have to write 9 lines of code each time

1 Like

this is just like that one devforum post that needs help with his flower

1 Like

Oh no, no, no, no. Please revamp your code and use Profile Service (AKA ProfileStore) instead, DataStores are very complex Profile Service makes this Easier.

Here’s how to set it up.

I love how you tell him to use ProfileService and then say “AKA ProfileStore” and then continue to send him a tutorial using ProfileService. :sob:

1 Like

what if in my game has players that already got presents and i want change it from datastore to profileservice, will it save the data?

It depends how you’re saving the presents but once you setup ProfileService or ProfileStore then you can just migrate all of the data in your other datastore either manually with a plugin like DataDelve or inside of the PlayerAdded function, just write some logic to access the previous datastore and transfer everything over to the ProfileStore.

1 Like

If im not wrong, No, Unless you dont set the name of the Store to your old one, But it could mess up Profile Service so just restart.