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