Saving a "StringValue"?

I want to be able to save a string value using a datastore. However, every time i try to, I get an error saying “Char is not a valid member of Player “Players.ImADumbN00bLol””.

local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetDataStore("Character")

local function saveData(player)
	local tableToSave = {
		player.Character 
	}

	local success, errorMessage = pcall(dataStore.SetAsync, dataStore, player.UserId, tableToSave)

	if success then 
		print("Data has been saved!") 
	else
		print("Data has not been saved!")
	end
end

--//leaderstats
game.Players.PlayerAdded:Connect(function(player) 
	local char = Instance.new("StringValue") 
	char.Name = "Char" 
	char.Value = "Character" 
	char.Parent = player

	local data = nil

	local success, errorMessage = pcall(function() 
		data = dataStore:GetAsync(player.UserId)
	end)

	if success and data then 
		char.Value = data[1] 
	else 
		print("The Player has no Data!")
		warn(errorMessage)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	saveData(player) 
end)

game:BindToClose(function()
	for _, player in ipairs(game.Players:GetPlayers()) do
		task.spawn(saveData, player) 
	end
end)

I think its because you’re using PlayerRemoving? I dont know if the character is removed before or after this event fires.

Dont think thats the case as the problem seems to be located on line 33.

That error doesn’t make sense for the code sample provided. Are you sure that it isn’t erroring in a different script?

Also, on line 6, you may have intended to do player.Char.Value instead of player.Character

issue seems to happen on the line

char.Value = data[1]

With what error? The error you provided does not match that.

Seem to have gotten the wrong error. The one i meant to refer to says “Unable to assign property Value. string expected, got nil”

Ok, in that case Data[1] is nil.

Refer to the second part of my initial reply

1 Like

Seem to have done the trick. Thanks!