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

i am unsure how to make my script check whether the player/model exists? (Solved)

I have tried to check if the humanoid exists however it is not working.


_G.dead = 0
local zombie = script.Parent.Parent.Zombie
local debounce = false

while wait(0.1) do
	local me = game.Workspace[tostring(_G.pl[math.random(1,#_G.pl)])]
	if me.Humanoid ~= nil then
		zombie:MoveTo(me:WaitForChild("HumanoidRootPart").Position)
	elseif not me.Humanoid then
		wait(1)
	end
end

i am really unsure, it would be a great help if anyone has any ideas

2 answers

if me.Humanoid ~= nil then

this is your problem, if Humanoid does not exist, it will throw an error that you tried to index nil value, to avoid this you could use FindFirstChild which will return nil in case where the child is not found, the best fit here though is FindFirstChildOfClass which works the same but will look for children of the specified class only, replace line 7 with this:

if me:FindFirstChildOfClass("Humanoid") then

Same situation is happening on line 9:

elseif not me.Humanoid then

This is a common mistake where people do something like this:

if something == nil then
	[...]
elseif something ~= nil then
	[...]
end

when they can just do this:

if something == nil then
	[...]
else
	[...]
end

You can do that too in your case, so the solution would be this:

 if me:FindFirstChildOfClass("Humanoid") then
	zombie:MoveTo(me:WaitForChild("HumanoidRootPart").Position)
else
	task.wait(1)
end

Prefer using task.wait over wait, it is the new version and has better performance. You can use FindFirstChild on line 6 too if it errors:

local me = game.Workspace:FindFirstChild(tostring(_G.pl[math.random(1,#_G.pl)]))

i fixed it i needed to add if not me:FindFirstChild("Humanoid")

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