Tycoon doesn't get destroyed when player leaves

--// Services \\--
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")

--// Remote Events \\--
local RemoteEvents = ReplicatedStorage:FindFirstChild("RemoteEvents")
local Notification = RemoteEvents:FindFirstChild("NotificationEvent")

--// Additional Variables \\--
local TycoonsHolder = workspace:FindFirstChild("Tycoons")
local TycoonCloneHolder 	= ServerStorage.TycoonCloneHolder
local TycoonTable = {}

--// Functions \\--

local function DestroyTycoon(player)
	for _, Tycoon in pairs(TycoonsHolder:GetChildren()) do

		if Tycoon:FindFirstChild("TycoonOwner") then
			
			local TycoonOwner = Tycoon:FindFirstChild("TycoonOwner").Value
			
			if TycoonOwner == player then
				
				Tycoon:Destroy()

				TycoonCloneHolder:FindFirstChild(Tycoon.Name).Parent = TycoonsHolder
				
				table.remove(TycoonTable, table.find(TycoonTable, player.Name))
				
				print(TycoonTable)

				print(player.Name.." has left the game. Successfully destroyed their tycoon!")
			end
		end
	end
end

local function CharacterAdded(character, SpawnPos)
	character.PrimaryPart.CFrame = SpawnPos.CFrame * CFrame.new(0,5,0)
	print("Loaded character to their island!")
end


Players.PlayerAdded:Connect(function(player)
	
	player.CharacterAdded:Connect(function(character)
		--// Variables \\--
		local Humanoid = character:FindFirstChild("Humanoid")
		local attachment = Instance.new("Attachment")
		local beam = Instance.new("Beam")
		local Forcefield = Instance.new("ForceField")

		attachment.Parent = character:FindFirstChild("HumanoidRootPart")
		beam.Parent = character:FindFirstChild("HumanoidRootPart")
		Forcefield.Parent = character

		if not character:FindFirstChild("ForceField") then
			local newForcefield = Instance.new("ForceField")
			newForcefield.Parent = character
		end	

		Humanoid.Seated:Connect(function(isSeated, seat)
			if isSeated then
				if seat:IsA("VehicleSeat") then
					if character:FindFirstChildOfClass("ForceField") then
						character:FindFirstChildOfClass("ForceField"):Destroy()
						print("Destroyed forcefield.")
						Notification:FireClient(player, "Forcefield")
					end
				end
			end
		end)

		character.ChildAdded:Connect(function(child)
			if child:IsA("Tool") then		
				if character:FindFirstChildOfClass("ForceField") then
					character:FindFirstChildOfClass("ForceField"):Destroy()
					print("Destroyed forcefield.")
					Notification:FireClient(player, "Forcefield")
				end
			end
		end)	

		Humanoid.Died:Connect(function()

			Humanoid:UnequipTools()
			local Backpack = player.Backpack:GetChildren()

			for _, tool in pairs(Backpack) do
				if tool:IsA("Tool") then
					tool:Destroy()
				end
			end

			if character:FindFirstChild("KillTag") then

				local Player = character.KillTag.Value
				local StatsFolder = Player:FindFirstChild("StatsFolder")
				local Kills = StatsFolder.Kills

				Kills.Value += 1

				local TargetStatFolder = game.Players:GetPlayerFromCharacter(character):FindFirstChild("StatsFolder")

				local Deaths = TargetStatFolder.Deaths
				Deaths.Value += 1
			end
		end)
	end)
	
	--// Stats \\--
	local StatsFolder = player:WaitForChild("StatsFolder")
	local OwnsTycoon  = StatsFolder:WaitForChild("OwnsTycoon")
	local ColorTheme1 = StatsFolder:WaitForChild("ColorTheme1")
	local ColorTheme2 = StatsFolder:WaitForChild("ColorTheme2")
	local ColorTheme3 = StatsFolder:WaitForChild("ColorTheme3")
	
	--// PlayerBool Stats \\--
	local PlayerBools   = player:WaitForChild("PlayerBools")
	local CurrentTycoon = PlayerBools:WaitForChild("CurrentTycoon")
	
	--// Tycoon Setup \\--
	local TycoonSetup   = ServerScriptService:FindFirstChild("TycoonSetup")
	local SetColorTheme = ServerScriptService:FindFirstChild("SetColorTheme")
	
	
	for _, Tycoon in pairs(TycoonsHolder:GetChildren()) do
		if Tycoon:FindFirstChild("Occupied").Value == false then
			if not table.find(TycoonTable, player.Name) then

				Tycoon:FindFirstChild("Occupied").Value = true
				table.insert(TycoonTable, player.Name)

				print(TycoonTable)

				local Components 		= Tycoon:FindFirstChild("Components")
				local Tycoon_Owner 		= Tycoon:FindFirstChild("TycoonOwner")
				local Cash_To_Collect 	= Tycoon:FindFirstChild("CashToCollect")
				local Owner				= Tycoon:FindFirstChild("Owner")
				local PlayerPicture		= Components:FindFirstChild("PlayerPicture"):FindFirstChild("ImageLabel")
				local Claimpad 			= Components:FindFirstChild("Claim Pad")
				local Claim 			= Claimpad:FindFirstChild("Pad")
				local Current_Owner 	= Claimpad:FindFirstChild("Gui"):FindFirstChild("CurrentOwner")
				local userId 			= player.UserId
				local thumbType 		= Enum.ThumbnailType.HeadShot
				local thumbSize 		= Enum.ThumbnailSize.Size420x420
				local content, isReady 	= Players:GetUserThumbnailAsync(userId, thumbType, thumbSize)

				Owner.Value = player.Name
				Tycoon_Owner.Value = player
				PlayerPicture.Image = content
				Current_Owner.Text = "Owner: "..tostring(Tycoon_Owner.Value)			

				player.RespawnLocation = Components:FindFirstChild("Spawn")
				CurrentTycoon.Value = Tycoon.Name

				local char = player.Character or player.CharacterAdded:Wait()
				if char then
					CharacterAdded(char, Components:FindFirstChild("Spawn"))
				end

				if OwnsTycoon.Value == false then							
					OwnsTycoon.Value = true
					print("New tycoon!")
				elseif OwnsTycoon.Value == true then
					Cash_To_Collect.Value = StatsFolder.TycoonSavedCash.Value
					TycoonSetup:Fire(Tycoon.Name, player)
					SetColorTheme:Fire(Tycoon, ColorTheme1.Value, ColorTheme2.Value, ColorTheme3.Value)
					print("Loading tycoon info.")
				end
			end
		end
	end
end)

Players.PlayerRemoving:Connect(DestroyTycoon)

I’m trying to destroy a player’s tycoon and it works about 90% of the time. I can’t figure out how to destroy the tycoon 100% of the time. There’s no errors but it seems as if it doesn’t get passed an if statement, PlayerRemoving doesn’t fire sometimes or something else causing the issue. TycoonOwner is an objectvalue and its value is assigned to the player when they join the game. Could TycoonOwner become nil if the player joins and leaves right away? Is there anything I can do to ensure this always works?

Thanks!

You could just use a numbervalue instead of a objectvalue and set the value to the Player’s UserId.

1 Like

Thank you for the suggestion. I’ll try that out. I’m trying to figure out as to why ObjectValues become nil after the player leaves as this should always work but it doesn’t a small amount of the the time. Any reason as to why?

It is probably because the Player instance gets destroyed once the player leaves. I would also recommend storing the player’s user id instead of the player instance itself as suggested by @SelectiveMattwest

2 Likes

I’m afraid of a values somehow becoming nil. I was thinking of possibly trying to link player’s userid with their corresponding tycoon for example:

local TycoonTable = {}


local function AddPlayer(player)
	for _, Tycoon in pairs(workspace.Tycoons:GetChildren()) do
		if not TycoonTable[player.UserId] and Tycoon:FindFirstChild("Occupied").Value == false then
			TycoonTable[player.UserId] = Tycoon
			Tycoon.Occupied.Value = true
		end
	end
	
	print(TycoonTable)
end

local function DestroyTycoon(player)

	for _, Tycoon in pairs(workspace.Tycoons:GetChildren()) do
		if Tycoon == TycoonTable[player.UserId] then
			Tycoon:Destroy()
			
		end
	end
	
	TycoonTable[player.UserId] = nil

	print(TycoonTable)
	
end

game.Players.PlayerAdded:Connect(AddPlayer)
game.Players.PlayerRemoving:Connect(DestroyTycoon)

Which would print out:

{
   ["Player1"] = Tycoon [1],
   ["Player2"] = Tycoon [2]
}

Is there anything I could improve from this and would this be better than using values stored in the tycoon?

Yeah, this should work. Also, an alternative to looping through the tycoons to find the player’s tycoon would be to name the tycoon model the player’s name. Then, you can do this to access the player’s tycoon.

workspace.Tycoons:FindFirstChild(player.Name)
1 Like

The error is not about firing, its about how you destroy the tycoon,you should save the tycoon owner name value in all the tycoon, and when a player leaves, it should loop through all the values of tycoon and check if it matches with player name

Then delete it

Don‘t see any issue?
Could you provide a video?
My tip is also using Zed‘s Tycoon Kit with the Save Version of it. To not hear the sound everywhere use this.

2 Likes

The bug is hard to replicate as it doesn’t happen often in game. However when it does happen it causes a slot to be filled up, ultimately preventing any new players from being able to play. I went ahead and used a table to keep track of all the tycoons and players instead.

1 Like