How to get ModuleScripts to keep their references after player resets when coding UI

I’ve set up my game so that my UI in stored in ReplicatedStorage because it apparently saves server memory. Along with this, the game follows Single-Script Architecture meaning my UI code is all in ModuleScripts.

Whenever a player resets however, this means I have to manually copy over the UI from ReplicatedStorage into PlayerGui. This would work, if the ModuleScripts did keep their references, which they don’t. This causes functions to stop working because they are editing references which no longer exist.
Currently, the ModuleScripts are placed inside a folder in ReplicatedStorage causing everything to be separated (also so that I can easily access them in code).

How do regular LocalScripts keep their references after a player resets? How can I get similar behaviour with ModuleScripts? Setting the UI to not ResetOnSpawn does not work because the UI is in a folder.

image
image

1 Like

Typically, local scripts are attached as children of the UI, so I think they get copied over along with the UI when the character respawns which is why the references are always up-to-date.

I think you’re going to need connect to the CharacterAdded event and handle updating the references yourself whenever the UI is copied into the player’s PlayerGui.

1 Like

Yes, what I thought. Was hoping I didnt have to reinitialize all the references but oh well.

Thanks

Sorry, but after doing some further testing, any UI that is set to ResetOnSpawn loses all functionality after reset.

The old UI is cleared out and then replaced with a fresh copy from ReplicatedStorage, then the ModuleScripts are reinitialized but no functionality comes. Any idea what might be causing this?

EDIT: Nevermind, seemed to have fixed it by itself?

You should consider using local script in players scripts and getting reference when gui is removed, this way you can avoid potential memory leak from gui re-spawning and re-iitiating scripts

EDIT: It’s pretty much better to disable ResetOnSpawn and create your custom function to do it, as it will give you more flexibility

Example:

local DefaultGuiPatterns = {}

local Constants = {
    ["shop"] = {
        DefaultColors = {
            ...
        },
        IsButtonVisible = false
    }
}
local Functions = {

    ["shop"] = function(Gui)
        Gui.Button.Visible = Constants.Shop.IsButtonVisible
        for i, frame in Gui:GetChildren() do
            frame.Color = Constants.Shop.DefaultColors[frame.Name] or Color3.new(1,1,1)
        end
    end

return DefaultGuiPatterns

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.