Error with load Color3

Hello, I have a very annoying problem when trying to load a color i catch error.

This error

image

Here’s load data function:

game.Players.PlayerAdded:Connect(function(Player)
	
	local HairColor = HairColorDataStore:GetAsync(Player.UserId)	
	
	Player.PlayerInfo.HairColor.Value = Color3.new(HairColor.RGBData[1], HairColor.RGBData[2], HairColor.RGBData[3])
	
end)

And here save data function:

game.ReplicatedStorage.DataEvents.SaveCharacterEvent.OnServerEvent:Connect(function(Player)
	
	local Character = Player.Character
	
	for _, Accessory in pairs(Character:GetChildren()) do	
		if Accessory:IsA("Accessory") then
			
			local Handle = Accessory:FindFirstChild("Handle")
			
			local RGBData = {
				R = Handle.Color.r,
				G = Handle.Color.g,
				B = Handle.Color.b
			}
			
			if Handle:FindFirstChild("HairAttachment") then
				
				local success, errormessage = pcall(function()
					HairColorDataStore:SetAsync(Player.UserId, RGBData)
				end)

				if success then
					print("Saved!")
				else
					print("Error!")
					warn(errormessage)
				end
				
			end
		end
	end 
end)

Three issues:

  1. The variable HairColor inside PlayerAdded stores the RGBData not HairColor.RGBData.
  2. You’re storing the colors as a dictionary, not as an array(therefore indexing them with 1, 2, 3 wont work).
  3. If a user joins for the first time, the script will error, because they don’t have any data.

Fix:

game.Players.PlayerAdded:Connect(function(Player)
	--also keep in mind, you have to pcall the datastore request, if it fails the script will break
	local HairColor = HairColorDataStore:GetAsync(Player.UserId)	
	local PlayerHairColor = Player.PlayerInfo.HairColor
	if HairColor then --if they have data, set the value
		--indexing HairColor with R/G/B because it was saved using this keys
		--using Color3.new instead of Color3.fromRGB because the values are in a range between 0 and 1
		PlayerHairColor.Value = Color3.new(HairColor.R, HairColor.G, HairColor.B)
	else --if they don't, set their default value
		PlayerHairColor.Value = Color3.fromRGB(0, 0, 0) --default value, black
	end 
end)
1 Like

Thank you very much for your quick help :slight_smile: