How do I prevent this error after character is reset?

Hi! So I have 2 GUI buttons. When you press one of them, it is supposed to change the trail of the player.

It works when the character is first loaded. However, once the character is reset or when LoadCharacter() is fired, the trail is not cloned and parented to the character again and is recognized as nil.

The server script:

game.Players.PlayerAdded:Connect(function(player)
	
	player.CharacterAdded:Connect(function(char)
		
        local trail = game.ReplicatedStorage.RainbowTrail:Clone()
		trail.Parent = char.Head
		
        local attachment0 = Instance.new("Attachment",char.Head)
		attachment0.Name = "TrailAttachment0"
		
        local attachment1 = Instance.new("Attachment",char.HumanoidRootPart)
		attachment1.Name = "TrailAttachment1"
		
        trail.Attachment0 = attachment0
		trail.Attachment1 = attachment1
		trail.Enabled = false
		
	end)
	
end)

game.ReplicatedStorage:WaitForChild("EnableTrail").OnServerEvent:Connect(function(player, trail1, trail2)
	trail1.Enabled = false
	trail2.Enabled = true
end)

The local script in the GUI button:

local Button = script.Parent
local gamepassID = 27311003
local mps = game:GetService("MarketplaceService")

local Plr = game.Players.LocalPlayer

local rainbowTrail = Plr.Character:WaitForChild("Head"):WaitForChild("RainbowTrail")
local shadowTrail = Plr.Character:WaitForChild("Head"):WaitForChild("ShadowTrail")

Button.MouseButton1Click:Connect(function()
	if mps:UserOwnsGamePassAsync(Plr.UserId, gamepassID) then
		game.ReplicatedStorage:WaitForChild("EnableTrail"):FireServer(shadowTrail, rainbowTrail)
	else
		mps:PromptGamePassPurchase(Plr, gamepassID)
	end
end)

The problem here is that in the localscript it defines rainbowTrail outside of the Button.MouseButton1Click event, it does not define it again every time the button is clicked, meaning if the trail that you set this variable to track is deleted, it does not track a new one that replaces it. The solution is to put the declarations of both rainbowTrail and shadowTrail inside of the Button.MouseButton1Click event. Probably.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.