Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a way that I can make a function that can fire from all server scripts?

Asked by 7 years ago

The question basically speaks for itself, this would be very useful in my new game.

1
I'd suggest BindableEvents, you can put a BindableEvent.Event:Connect(function(Arguments) end) in one script, and BindableEvent:Fire(Arguments) in all the other scripts that you want to use it from. BindableEvent is an Instance that you should probably parent in ServerStorage or ServerScriptService if you don't want the client to see it. (They won't be able to use it though so it doesn't matter.) RubenKan 3615 — 7y
0
ok, thx JakePlays_TV 97 — 7y

2 answers

Log in to vote
1
Answered by 7 years ago

Okay this is rather simple

_G.FunctionName = function(Variables) -- Define the function
    -- Whatever you want to do
end

In another script

_G.FunctionName(Variables)
0
This creates a global function, accessed via _G M9_Sigma 35 — 7y
0
I'd personaly suggest to never use _G as theres always a way around it. Like Modules or BindableEvents/Functions RubenKan 3615 — 7y
0
Thanks JakePlays_TV 97 — 7y
Ad
Log in to vote
0
Answered by
ee0w 458 Moderation Voter
7 years ago

This is fairly simple to do. And that is using a ModuleScript. To simplify things; a ModuleScript is a special kind of script that can be obtained using the require() function from any script, anywhere (as long as the script can obtain it. ex: a LocalScript cannot access ServerStorage - so it would error.)

ModuleScripts work in the same manner as normal Scripts, but functions are named slightly different. I'll show you an example:

-- ModuleScript

local module = {}
-- any functions/variables in here will be part of the module.

function module.printMyFavouriteAnimal()
    print("probiker123's favourite animal is a dog!")
end

return module

As you may notice, the function name is slightly different than what you'd expect. But it's very simple to understand. Rather than using function functionName(), instead you use function moduleName.functionName() so since "module" is the module, the function would be module.functionName().

Now that you have the ModuleScript setup, it's pretty straightforward from here. In ANY script (that, of course, can access it) you simply type, local moduleName = require(script location). This requires the module. Now to run the function from the script, you type the variable name (that you created within the server/local script) and then the function name. So here's how you'd do it.

-- Server Script
local myModule = require(game.ReplicatedStorage:WaitForChild("ModuleScript"))

myModule.printMyFavouriteAnimal()

> "probiker123's favourite animal is a dog!"

Hope this helped!

0
I would suggest using this over the global table. mraznboy1 194 — 7y

Answer this question