I'm an idiot. Players don't have torsos. Please commence slapping me in the face...
Original post:
I wrote this code to make an NPC watch the player closest to it, as long as the closest player is no greater than 40 studs away. At the beginning of my function, I loop through each player in the server with a for loop, then I do a check to make sure the player's character, humanoid, and torso exists. Oddly enough, however, I continue to get this output error;
15:07:37.911 - Torso is not a valid member of Player
15:07:37.912 - Script 'Workspace.Bot.FaceEnemyScript', Line 24
15:07:37.913 - Stack End
The areas of code related to the problem are as follows;
local hum = plr.Character:FindFirstChild("Humanoid")
local tor = plr.Character:FindFirstChild("Torso")
if plr.Character and tor and hum and hum.Health > 0 then
---
if plr then
local direction = (plr.Torso.Position - bot.Torso.Position) * Vector3.new(1, 0, 1) --This is the actual line the error appears on.
bot.Torso.CFrame = CFrame.new(bot.Torso.Position,bot.Torso.Position + direction)
end
And my entire code, for reference;
local bot = script.Parent.NPC
function findNearestTorso()
local closestDistance = 40
local target = nil
for index, plr in pairs(game.Players:GetPlayers()) do
local hum = plr.Character:FindFirstChild("Humanoid")
local tor = plr.Character:FindFirstChild("Torso")
if plr.Character and tor and hum and hum.Health > 0 then
local distance = (tor.Position - bot.Torso.Position).magnitude
if distance > closestDistance then
closestDistance = distance
target = plr
end
end
end
return target
end
while true do
wait()
local plr = findNearestTorso()
if plr then
local direction = (plr.Torso.Position - bot.Torso.Position) * Vector3.new(1, 0, 1)
bot.Torso.CFrame = CFrame.new(bot.Torso.Position,bot.Torso.Position + direction)
end
end
If the torso doesn't exist the code should skip everything else and move on to the next player in the server. If none of the players in the server have a torso that exists, then the function should return nil and never pass the if statement on line 23. Obviously it must not work like this...

1 comment
It's possible to delete posts, just in case you feel like this post has no purpose anymore. The button is on the right side of your screen.