Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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

2 comments

0

thank you i didnt realise i did this

0

Its a common error, easy to miss when looking for why.

This discussion is preserved as it was. New answers, comments, and votes are closed.