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 2 years 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

01wait(2)
02local runService = game:GetService("RunService")
03local Players = game:GetService("Players")
04 
05local humanoid = script.Parent
06local root = humanoid.Parent.HumanoidRootPart
07 
08function findPlayer()
09    local playerList = Players:GetPlayers()
10    for i, player in pairs(playerList) do
11        print("finding player")
12        if (root.Position - player.Character.HumanoidRootPart.Position).Magnitude <= 5 then
13            print("found player")
14            return player      
15        end
View all 28 lines...

1 answer

Log in to vote
1
Answered by 2 years ago
Edited 2 years 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:

01wait(2)
02local runService = game:GetService("RunService")
03local Players = game:GetService("Players")
04 
05local humanoid = script.Parent
06local root = humanoid.Parent.HumanoidRootPart
07local Victim
08 
09function findPlayer()
10    local playerList = Players:GetPlayers()
11    for i, player in pairs(playerList) do
12        print("finding player")
13        if (root.Position - player.Character.HumanoidRootPart.Position).Magnitude <= 5 then
14            print("found player")
15            return player      
View all 28 lines...
0
thank you i didnt realise i did this Not_prototype 50 — 2y
0
Its a common error, easy to miss when looking for why. Jay123abc2 241 — 2y
Ad

Answer this question