Can't pass local variables to functions in the same script

local Kills = 0
local QuestComplete = game.ReplicatedStorage.QuestComplete
local QuestOne = game.ReplicatedStorage.QuestOne
local SQuestOne = game.ReplicatedStorage.SQuestOne

QuestOne.OnServerEvent:Connect(function()
	print("OMG ITS RUNNING WOW")
	Running = true
end)

while Running do 
		SQuestOne.Event:Connect(function(Player)
		print("HOLYCRAP ITS WORKING")
		Kills = Kills + 1
		print("YAYEET"..tostring(Kills))
		Counting = true
		LocalPlayer = Player
		print(tostring(LocalPlayer).."OOMGOMGOMG")
	end)
end

while Counting do 
	if Kills == 5 then
		print("OMG ITS FINISHED WOW")
		QuestComplete:FireClient(LocalPlayer)
		Kills = 0
		Counting = false
	end
end

(Please ignore my overzealous prints.)

I’m trying to set Running to true, but it doesn’t seem to get registered as a variable. It prints nil, and I don’t seem to be able to pass it. Does the script re-read my variables every time a function runs?

Running is only defined in the ServerEvent function, so it doesn’t exist outside of that scope. You need to make it a Global variable by defining Running at the top of your script with the rest of your variables.

Also, you shouldn’t have an event inside of a while loop, as every pass of the loop will create a new listener. You should create the event, and inside of it check if Running is true.

SQuestOne.Event:Connect(function(Player)
     if not Running then return end
     -- do stuff
end)

For the while Counting do loop, you will need a wait() statement or else the loop will crash. You can make Kills an IntValue Object, and connect it to a .Changed event

local Kills = game.ReplicatedStorage.Kills -- Object
Kills.Changed:Connect(function()
     if Kills.Value == 5 then
          -- do stuff
     end
end)
2 Likes

It’s not defined as a local in there so no. It’s visible in the entire script. The problem is the script is hitting the while Running check before it ever turns true.

It still has the same error even after defining it as a local variable.

The solution to the issue was to create an Instance.new(“BoolValue”).