Variable in a ModuleScript won't replicate to the caller

I have a local script that manages selecting units in a real time strategy game (this is explained in a bit more detail in a separate thread). I want to separate the code in module scripts so that it is more organized and easier to read.

There is a particular module script that I am having issues with. Allow me to explain the concept of the game that it handles, so that the rest of this post makes more sense:
When a player selects units, he / she can give them orders by right-clicking anywhere on the map. However, giving commands to units via right-clicking is not supposed to be possible while the mouse is hovered over an element of the command bar, such as a command button.
In other words: the user must be aiming at a visible portion of the map in order to tell units to move to that position.

Now, here is the issue:
The module script returns a boolean, representing whether or not the mouse is hovering over an element of the command bar. However, I have discovered that the caller does not receive any changes made by the module script. Here is the code:

local UserInputService = game:GetService("UserInputService")

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
local mainScreen = playerGui:WaitForChild("Roframes"):WaitForChild("Screen")
local commandBar = mainScreen:WaitForChild("CommandBar")

local mouseOverGUI = false

for _, guiElement in pairs(commandBar:GetChildren()) do
	guiElement.InputChanged:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseMovement then
			print("true")
			mouseOverGUI = true
		end
	end)
	guiElement.InputEnded:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseMovement then
			print("false")
			mouseOverGUI = false
		end
	end)
end

return mouseOverGUI

All I want to know is if the caller can receive updates from the module script, or if I have to program this another way. I briefly searched the forum for answers, but found nothing. I also tried setting mouseOverGUI to a global variable, but nothing changed.

Any help on this issue would be greatly appreciated.

The code in module scripts will only run once, when it is required, hence why it only returns false. You can receive updates from the module script but it will require you to script your own custom signal class or you can use Bindable events.

1 Like