This code is supposed to have a player teleport wherever their mouse is at when they press "e" and also for the player to be able to teleport even after they die but when I run it, I get an error in the output saying, "Attempt to index nil with Character" on the first line in this block of code. How do I fix this?
game:GetService("Players").PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(plr) plr = game.Players.LocalPlayer humanoid = plr.Character.HumanoidRootPart mouse = plr:GetMouse() mouse.KeyDown:Connect(function(key) if key == "e" then if mouse.Target then humanoid.CFrame = CFrame.new(mouse.Hit.x,mouse.Hit.y + 5,mouse.Hit.z) plr:WaitForChild("Humanoid").Died:Connect(function() player.CharacterAdded:Wait() mouse.KeyDown:Connect(function(key) if key == "e" then if mouse.Target then humanoid.CFrame = CFrame.new(mouse.Hit.x,mouse.Hit.y + 5,mouse.Hit.z) end end end) end) end end end) end) end)
The server does not have access to :GetMouse() therefore your code won't run. To fix this, we can make a localscript and put your code inside of it, then inside of the serverscript we can make it clone the localscript into the player whenever they join.
Localscript Code:
plr = game.Players.LocalPlayer humanoid = plr.Character.HumanoidRootPart mouse = plr:GetMouse() mouse.KeyDown:Connect(function(key) if key == "e" then if mouse.Target then humanoid.CFrame = CFrame.new(mouse.Hit.x,mouse.Hit.y + 5,mouse.Hit.z) end end end)
Serverscript Code:
game.Players.PlayerAdded:Connect(function(plr) plr.CharacterAdded:Connect(function(chr) script.LocalScript:Clone().Parent = chr --Obviously localscript is just what I called it, and script is just the parent I set. You can change it all you want. end) end)
(For my example, the localscript is inside of the script. You could set it to whatever you want though.)
If this helped make sure to accept my answer. ^w^