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

Can anyone help me with my AI script running through a function for no point?

Asked by 1 year ago

its my first time making an AI and the error i have came across is at the if "Victim == nil" my problem with it is that even if it finds a player it continues to go through the function even though the scripts says that the victim variable is not nil

wait(2)
local runService = game:GetService("RunService")
local Players = game:GetService("Players")

local humanoid = script.Parent
local root = humanoid.Parent.HumanoidRootPart

function findPlayer()
    local playerList = Players:GetPlayers()
    for i, player in pairs(playerList) do
        print("finding player")
        if (root.Position - player.Character.HumanoidRootPart.Position).Magnitude <= 5 then
            print("found player")
            return player       
        end
    end
end

while true do
    wait(.1)
    local Victim
    if Victim == nil then
        Victim = findPlayer()
        print("finding player")
    else
        print(Victim)
    end
end

1 answer

Log in to vote
1
Answered by 1 year ago
Edited 1 year ago

After looking at the script, I have spotted the issue. You declare the victim value in the loop, this means it's being reset to nil every time the loop runs again. Simply, move the value to the start. So, the code will become something like this:

wait(2)
local runService = game:GetService("RunService")
local Players = game:GetService("Players")

local humanoid = script.Parent
local root = humanoid.Parent.HumanoidRootPart
local Victim

function findPlayer()
    local playerList = Players:GetPlayers()
    for i, player in pairs(playerList) do
        print("finding player")
        if (root.Position - player.Character.HumanoidRootPart.Position).Magnitude <= 5 then
            print("found player")
            return player       
        end
    end
end

while true do
    wait(.1)
    if Victim == nil then
        Victim = findPlayer()
        print("finding player")
    else
        print(Victim)
    end
end
0
thank you i didnt realise i did this Not_prototype 50 — 1y
0
Its a common error, easy to miss when looking for why. Jay123abc2 241 — 1y
Ad

Answer this question