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
01 | wait( 2 ) |
02 | local runService = game:GetService( "RunService" ) |
03 | local Players = game:GetService( "Players" ) |
04 |
05 | local humanoid = script.Parent |
06 | local root = humanoid.Parent.HumanoidRootPart |
07 |
08 | function 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 |
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:
01 | wait( 2 ) |
02 | local runService = game:GetService( "RunService" ) |
03 | local Players = game:GetService( "Players" ) |
04 |
05 | local humanoid = script.Parent |
06 | local root = humanoid.Parent.HumanoidRootPart |
07 | local Victim |
08 |
09 | function 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 |