I am trying to save playerdata but the issue is, is that, this code, if someone leaves, while I am playing, when they rejoin, they end up with my stats. It seems when they are leaving the data is saved for the wrong player. How can I fix this? If only I can connect an event when a SPECIFIC player is leaving. Like game.Players.asadefa.Removing:Connect()

The following code is in a PlayerAdded:Connect() function

        local ChangeData = Instance.new("BindableFunction", BFuncionsF)
	ChangeData.Name = Player.UserId
	local S, Data = pcall(function()
		local Data = Database:GetAsync("USER"..Player.UserId) or {}
		local DataTable = {
			['IsOP'] = Data['IsOP'] or 0,
			['Level'] = Data['Level'] or 0,
			['LvlXP'] = Data['LvlXP'] or 0,
			['Money'] = Data['Money'] or 0,
			['Crystal'] = Data['Crystal'] or 0,
			['Bonker'] = Data['Bonker'] or 0,
			['Sword'] = Data['Sword'] or 0,
			['Hammer'] = Data['Hammer'] or 0,
			['Knife'] = Data['Knife'] or 0,
			['Brick'] = Data['Brick'] or 0,
			['NeutronHammer'] = Data['NeutronHammer'] or 0,
			['DraviteHammer'] = Data['DraviteHammer'] or 0,
			['SpellPower'] = Data['SpellPowerSpells'] or 0,
			['FireSpells'] = Data['FireSpells'] or 0,
			['IceSpells'] = Data['IceSpells'] or 0
		}
		return DataTable
	end)
	AllocateItems(Data, Player)
	local Leaderstats = Instance.new("BoolValue", Player)
	Leaderstats.Name = "leaderstats"
	local Level = Instance.new("IntValue", Leaderstats)
	Level.Name = "Level"
	Level.Value = Data['Level']
	local Money = Instance.new("IntValue", Leaderstats)
	Money.Name = "Money"
	Money.Value = Data['Money']
	local Crystals = Instance.new("IntValue", Leaderstats)
	Crystals.Name = "Crystals"
	Crystals.Value = Data['Crystal']
	ChangeData.OnInvoke = function(Type, Value)
		Data[Type] = Value
		if Type == Level.Name then
			Level.Value = Value
		elseif Type == Money.Name then
			Money.Value = Value
		elseif Type == Crystals.Name then
			Crystals.Value = Value
		end
	end
	game:GetService("Players").PlayerRemoving:Connect(function(Player)
		Database:SetAsync("USER"..Player.UserId, Data)
	end)

2 comments

0

Is this the whole script? I

0

I'm thinking you either have a global data or a global player variable somewhere but I can't tell without the whole script.