There are several problems with your script. Those are:
KeyDown and KeyUp are both deprecated, so you have to use UserInputService instead.
connect is also deprecated. The new method is Connect
The Lighting is not a place for storage, you are supposed to use ReplicatedStorage and ServerStorage
And the most important: Other players will not see the trail if FilteringEnabled is on. so you would use remote events and functions.
But the one causing your issue is that you have to connect the function to CharacterAdded if you want it to work if they respawn.
Solution:
Put the Trail inside ServerStorage
Put a RemoteFunction called CreateTrail in the ReplicatedStorage
Put a RemoteEvent called EnableTrail in the ReplicatedStorage
LocalScript
local player = game.Players.LocalPlayer
local Replicated = game:GetService("ReplicatedStorage")
local CreateTrail = Replicated:WaitForChild("CreateTrail")
local EnableTrail = Replicated:WaitForChild("EnableTrail")
local UserInputService = game:GetService("UserInputService")
local trail
player.CharacterAdded:Connect(function(char)
trail = CreateTrail:InvokeServer(char:WaitForChild("Head"),char:WaitForChild("Torso"))
end)
UserInputService.InputBegan:Connect(function(input,processed)
if trail == nil then return end
if processed then return end
if input.KeyCode == Enum.KeyCode.Zero then
EnableTrail:FireServer(trail,true)
end
end)
UserInputService.InputEnded:Connect(function(input,processed)
if trail == nil then return end
if processed then return end
if input.KeyCode == Enum.KeyCode.Zero then
EnableTrail:FireServer(trail,false)
end
end)
Script in ServerScriptService
local Replicated = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local Trail = ServerStorage:WaitForChild("Trail")
local CreateTrail = Replicated:WaitForChild("CreateTrail")
local EnableTrail = Replicated:WaitForChild("EnableTrail")
CreateTrail.OnServerInvoke = function(player,p1,p2)
local new = Trail:Clone()
local a1 = Instance.new("Attachment")
a1.Name = "Attachment1"
a1.Parent = p1
local a2 = Instance.new("Attachment")
a2.Name = "Attachment2"
a2.Parent = p2
new.Attachment0 = a1
new.Attachment1 = a2
new.Enabled = false
new.Parent = p1
return new
end
EnableTrail.OnServerEvent:Connect(function(player,trail,enable)
if trail:IsA("Trail") then
trail.Enabled = enable
end
end)
2 comments
But if it fires when the player dies, after the player respawns, the trail will be removed again.
add Wait(6) before the code that gives the player the trail