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

How can I fix this issue "attempt to index nil with 'Head' "?

So, I'm trying to make a little GUI that allows you to input a target name to teleport to that player for my game in Roblox Studio. I have a localscript inside of my "Teleport" button with the following code:

local btn = script.Parent -- finds the teleport button
local display = script.Parent.Parent.NameInput -- finds the textbox where you input the target
local input = display.Text -- gets the text value from the textbox
local plr = game.Players.LocalPlayer -- finds your localplayer to find the character
local char = plr.Character -- finds your own character

btn.MouseButton1Down:Connect(function() -- executes the script when pressed
-- This "pos" (short for position) finds the CFrame of a player's head
-- The "input" variable below is used inside the path so it should replace "input" with, lets say, JohnDoe
	local pos = game.Workspace:FindFirstChild(input).Head -- 
	char.HumanoidRootPart.CFrame = CFrame.new(pos); -- sets your local character's humanoidRootPart CFrame to the target's head CFrame
end)

Btw, I used the target's head because I want it to work for R15 and R6 if that makes sense.

I get this error here: Players.Voltaicmimic.PlayerGui.Teleport.TeleportFrame.TextButton.LocalScript:9: attempt to index nil with 'Head' - Client - LocalScript:9

1 comment

0

I hope this makes sense. This is my first ever question here.

1 answer

✓ Accepted answer

A couple changes to prevent future errors. I hope this fixes your issue. Start learning the habit of reality checks and waitForChild It prevents scripts from loading to quick errors.

local display = script.Parent.Parent:WaitForChild("NameInput")

local char = plr.Character or plr.CharacterAdded:wait()

local pos = game.Workspace:FindFirstChild(input):FindFirstChild("Head")
if pos then
char.HumanoidRootPart.Position = pos.Position
end

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