So I have a PlayerAdded event in a server-side script. When the player joins, a ball is created and named what the players name is.
I am trying to assign a global variable outside of the function to the ball that is created inside the function, because I need to do things to the ball elsewhere server-side.
Use a module to create/store information about the ball and who owns it. Modules are a great way for global things.
For instance you could have something like module:CreateBall(Player) then store the ball in a table with the players name. This way you can easily call upon it at a later time
A basic example is to have a module in ServerStorage named “Balls”
local Balls = {}
local playerballs = {}
function Balls.GetBalls()
return playerballs
end
function Balls.NewBall(player)
if playerballs[player] then
playerballs[player]:Destroy() --destroy their ball if they already have one
end
--code for creating the ball goes here
--
playerballs[player] = ball --ball is the ball you created a moment ago
return ball
end
game.Players.PlayerRemoving:Connect(function(player) --references to players remain even after they leave, so we have to manually do this
local ball = playerballs[player]
if ball then
ball:Destroy()
playerballs[player] = nil
end
end)
return Balls
In your server script:
local Balls = require(game.ServerStorage:WaitForChild("Balls"))
game.Players.PlayerAdded:Connect(function(player)
local ball = Balls.NewBall(player)
--do something with the ball here if you'd like
end)
If you’re in another script and you want to access a player’s ball, you can do
local Balls = require(game.ServerStorage:WaitForChild("Balls"))
--code somewhere:
local ball = Balls.GetBalls()[player]
if ball then
--code
end
--
If you want to avoid the module approach for whatever (ill) reason, you could parent the objects to a folder. In your other server scripts, you can reference the saved objects inside that folder to do whatever you need.
Surprisingly, you can, so long as the instance is replicated on both environments. I can have a variable referencing a part in the Workspace on the server and send it through a remote to the client. The client, likewise, can do the same if the part it indexes exists on the server.