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

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

Asked by 3 years ago

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

0
I hope this makes sense. This is my first ever question here. Voltaicmimic 43 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago

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
Ad

Answer this question