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

Another 'attempt to index a nil value', please help?

-- Zombie Controller
-- by alphagamer150

-- Get services
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")

-- Create varibles
local Zombie = script.Parent

-- Main Loop
-- while not Python:
while wait() do
	local PlayerList = Players:GetPlayers()
	local LowestDistance = 0
	local ClosestPlayer
	for i = 1, #PlayerList do
		local PlayerPos = game.Workspace:FindFirstChild(PlayerList[i].Name).HumanoidRootPart.Position
		local ZombiePos = Zombie.HumanoidRootPart.Position
		print(PlayerPos)
		if (PlayerPos - ZombiePos).magnitude < LowestDistance then
			print("Test")
		end
	end
end

Script above keeps giving me 19:36:12.091 - Workspace.Zombie.Script:18: attempt to index a nil value

3 comments

0

we can't help you if you don't show line 18

0

Fixed

0

try local PlayerPos = game.Workspace:WaitForChild(PlayerList[i].Name).HumanoidRootPart.Position

1 answer

Their character may not have spawned yet, causing FindFirstChild to return nil. Additionally, I wouldn't recommend searching for characters using the username in the Workspace - imagine someone named Model joining your game and causing weird things to happen. Instead, I'd recommend using the Player.Character property. If they don't have one, use Player.CharacterAdded to wait for it. Here's an example.

local player = PlayerList[i]
local character = player.Character or player.CharacterAdded:Wait()
local rootPartPos = character:WaitForChild('HumanoidRootPart').Position

-- ...

Although, if you're yielding like this (which may pause the script for whatever amount of time), I'd recommend using spawn or coroutines to run this in parallel rather than one at a time. Advice beyond that is outside the scope of this answer, but yeah. Your issue is that either the character or HumanoidRootPart don't exist. Since it's most likely the former, here.

3 comments

0

"un this in parallel rather than one at a time." coroutines don't run in true parallel.

0

@incapaxx we don't need to use calculations in parallel, we're yielding, via :Wait() and WaitForChild, those can be executed in parallel using spawn

2

It's not necessarily "true parallel", but that doesn't matter

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