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

[SOLVED] How would you share a variable across scripts?

Hey guys, my question for now is:

How would you make a variable usable by various scripts in the game?

Example -

MainScript (Script #1)

NiceName = Johny

print(NiceName.."Is printed from the main script!")


--SOMEHOW "SHARE" IT

MinorScript (Script #2)

print(NiceName.."Is printed from another script!") --NiceName should be Johny, as declared in script #1

Thanks in advance! Also, try to not make something This thing you should but you don't understand, then do this which you also don't understand :). And if there is no really simple solution, atleast try to explain well. Thx.

EDIT: For some reason, bold and italic doesn't work >.>

2 comments

0

remote events

2

There are many ways to do this: modules, global variables (_G), remotes or bindables, etc

1 answer

✓ Accepted answer

You can share variables through many ways. The one I use more is through global variables (_G), which they store a variable globally, bring accessed through many scripts. An example would be this:

-- A script
_G.variableName = "Nathan"

Then another script

-- Another script
print(_G.variableName) -- Prints "Nathan"
-- "MAKE SURE THE NAMES ARE THE SAME"

Another way are the Bindable Events/Functions, which are normally used for triggerers in the server. They can only be used through server scripts, if you want to communicate through Server - Client, use RemoteEvents or RemoteFuncttons . An example can be this one:

-- A script
local event = game:GetService("ReplicatedStorage"):WaitForChild("BindableEvent")

function onClicked(value)
	local value = script.Parent.Money.Value
	event:Fire(value)
end

script.Parent.MouseClick:Connect(onClicked)

BindableEvent

-- Another Script
game.ReplicatedStorage.BindableEvent.Event:Connect(function(value)
	print(value)
end

I don't know well how does a bindable event work, as I normally use _G values, but hope this works! Please accept the answer if it helped.

1 comment

0

For the bindable it's Event, not OnEvent

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