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

attempt to index local 'char' (a nil value)?

Asked by 6 years ago
Edited 6 years ago
mob = script.Parent.Parent
hum = script.Parent.Parent:WaitForChild("Humanoid")
torso = script.Parent.Parent:WaitForChild("UpperTorso")
runAnim = hum:WaitForChild("RunAnim")
anim = hum:LoadAnimation(runAnim)
stayOnTarget = nil
maxRange = 50
findRange = 30

function attack(attacker)

    repeat
        wait()
        local attackPos = attacker.HumanoidRootPart.Position
        local distance = (attackPos - torso.Position).magnitude

        if distance <= maxRange then
            hum.WalkToPoint = attackPos
        else
            stayOnTarget = nil
            break
        end
    until false
end

while wait() do
    for index, player in pairs(game.Players:GetPlayers()) do
        print(player.Character)
        local char = player.Character --goes wrong here
        print(player.Character)
        local Distance = (torso.Position - char.HumanoidRootPart.Position).magnitude

        if Distance <= findRange then
            attacker = player.Character
            attack(attacker)
        end
    end
end

I tried player.Character or player.CharacterAdded:wait() but that doesn't change a thing, it only changes the error enough for me to know that I can't get the character? error: attempt to index local 'char' (a nil value)

1 answer

Log in to vote
0
Answered by
MrNicNac 855 Moderation Voter
6 years ago

It's possible for the character to just not exist yet or may not be available in some instances. You should guard against this by performing a check to be sure the variable char is set.

local char = player.Character
if (char) then
    -- The rest of your code here
end
Ad

Answer this question