I recently decided to better organize my scripts in the game I’m developing. I start with the client, since by comparison, I have more local scripts than server scripts and modules being used within the game.
Well, researching in the community, I found several tips to optimize my local scripts. I saw several developers using modules and only one script to satisfy the entire UI. I tried but I think I’m going the wrong way. I have some questions:
Main Local Script
local LocalPlayer = game.Players.LocalPlayer or game.Players.PlayerAdded:Wait()
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")
local PGuiModule = require(script:WaitForChild("GuiVar"))
PGuiModule.HouseGui.CloseHouseFrame.MouseButton1Click:Connect(function()
end)
ModuleScript
local PGuiModule = {}
local LocalPlayer = game.Players.LocalPlayer or game.Players.PlayerAdded:Wait()
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")
PGuiModule.HouseGui = {
BuyHouseFrame = PlayerGui:WaitForChild("HouseGui").BuyHouseFrame;
PaintHouseFrame = PlayerGui.HouseGui.PaintHouseFrame;
CloseHouseFrame = PlayerGui.HouseGui.BuyHouseFrame.Background.Close
}
return PGuiModule
To be able to use less memory with variable what is the best way to store these variables?
May i use only one script for all children of StarterGui?
For the LocalScript (and ModuleScript), or game.Players.PlayerAdded:Wait() is not necessary as when the Player joins, the LocalScript will Automatically run for that Player, However with the Players Character, and many other aspects, It may not Load immediately, So that’s why you do this:
local Char = Player.Character or Player.CharacterAdded:Wait()
Referencing LocalPlayer in ModuleScripts is safe only as long as they run in a local context otherwise it will produce an error.
In terms of memory it is better to have variables defined with the local keyword as after they are not used in the code anymore they will be garbage collected, although while tables are garbage collected after they are not referenced in the code anymore, tables’ keys and values don’t so they will be kept in memory until the table is not used anymore except for weak tables.
I would save variables in the LocalScript and if you really want to avoid writing them in each script you can make a function in the module script which returns them.