I keep getting an error that says Workspace.Evil Gingerbread Man LVL 1…EnemyController:24: attempt to index nil with ‘Position’ -
This is the code
local targetDistance = script:GetAttribute("TargetDistance")
local stopDistance = script:GetAttribute("StopDistance")
local damage = script:GetAttribute("Damage")
local attackDistance = script:GetAttribute("AttackDistance")
local attackWait = script:GetAttribute("AttackWait")
local lastAttack = tick()
function findNearestPlayer()
local playerList = Players:GetPlayers()
local nearestPlayer = nil
local distance = nil
local direction = nil
for _, player in pairs(playerList) do
local character = player.Character
if character then
local distanceVector = player.Character.HumanoidRootPart.Position - root.Position
if not nearestPlayer then
nearestPlayer = player
distance = distanceVector.Magnitude
direction = distanceVector.Unit
elseif distanceVector.Magnitude < distance then
nearestPlayer = player
distance = distanceVector.Magnitude
direction = distanceVector.Unit
end
end
end
return nearestPlayer, distance, direction
end
RunService.Heartbeat:Connect(function()
local nearestPlayer, distance, direction = findNearestPlayer()
if nearestPlayer then
if distance <= targetDistance and distance >= stopDistance then
humanoid:Move(direction)
else
humanoid:Move(Vector3.new())
end
if distance <= attackDistance and tick() - lastAttack >= attackWait then
lastAttack = tick()
nearestPlayer.Character.Humanoid.Health -= damage
end
end
end)
Thanks for your help