Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to fix "Attempt to index nil with Character?"

Asked by 4 years ago
Edited 4 years ago

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)
0
server doesnt have a local player. mouse cannot be obtained through the character. just create your mouse code everytime the player spawns?? :thonk: Fifkee 2017 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago

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^

0
Also, "Player.CharacterAdded" doesn't return a player. It returns the character. youtubemasterWOW 2741 — 4y
Ad

Answer this question