Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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)

1 comment

0

server doesnt have a local player. mouse cannot be obtained through the character. just create your mouse code everytime the player spawns?? :thonk:

1 answer

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^

1 comment

0

Also, "Player.CharacterAdded" doesn't return a player. It returns the character.

This discussion is preserved as it was. New answers, comments, and votes are closed.