Why Is variable changed in my function not being seen outside of function

Ok, So I’m Wondering why is that when my CorruptionBall is touched. The “touched” Variable is set to true but its not being saved out side of the touch function. It is seen as false outside of the Touched function? My goal is to have the “touched” variable set to true upon touched and seen outside of the function so other things may happen. Thanks

PS: This is NOT in a local script but regular script

local touched = false
	local function CorruptionBall(offset)
		local tempCorruptionBall = game.ReplicatedStorage.Misc.CorruptionBall:Clone()
		touched = false
		tempCorruptionBall:SetPrimaryPartCFrame(CFrame.new(blob.Position)) 
		tempCorruptionBall.Parent = game.Workspace.Temp			

		tempCorruptionBall.Hitbox.Touched:connect(function(hit)
			local char = hit.Parent
			local hum = char:FindFirstChild("Humanoid")	
			if hum then
				touched = true				
			end
			if touched then
				print("Touched")
			end
			
		end)
		if touched then
			Explode(tempCorruptionBall.Hitbox)
			tempCorruptionBall:Destroy()	
		end
		if touched == false then
			wait(3)
			Explode(tempCorruptionBall.Hitbox)
			tempCorruptionBall:Destroy()
		end
			
	end

Because your touched function will never even run because it’s in another function which is never called, the CorruptionBall function to be exact

Thanks for the suggestion, but it is being called, I have the prints there to test it. I solved my problem. The function was being called AFTER the if statements. So the touched variable was being changed but only after the IF statements were declared. Thanks for trying!

He’s right though, in the portion of the script you shared no call to “CorruptionBall()” was made.

local touched = false

local function CorruptionBall(offset)
	local tempCorruptionBall = game.ReplicatedStorage.Misc.CorruptionBall:Clone()
	touched = false
	tempCorruptionBall:SetPrimaryPartCFrame(CFrame.new(blob.Position)) 
	tempCorruptionBall.Parent = game.Workspace.Temp			

	tempCorruptionBall.Hitbox.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("HumanoidRootPart") then
			local char = hit.Parent
			local hum = char:FindFirstChild("Humanoid")	
			if hum then
				touched = true
				print("Touched")
			end
			
			if touched then
				Explode(tempCorruptionBall.Hitbox)
				tempCorruptionBall:Destroy()	
			end
			
			if not touched then
				task.wait(3)
				Explode(tempCorruptionBall.Hitbox)
				tempCorruptionBall:Destroy()
			end
		end
	end)
end

Your issue was that when the function is called those conditional statements are only ever executed once (even though they are waiting for a touch condition to become true), moving those conditional statements into the function connected to the “Touched” event is the fix.

1 Like