diff --git a/Assets/Scripts/WefLab/WefLabWebSocketClient.cs b/Assets/Scripts/WefLab/WefLabWebSocketClient.cs index 56755ff7d..815c5479c 100644 --- a/Assets/Scripts/WefLab/WefLabWebSocketClient.cs +++ b/Assets/Scripts/WefLab/WefLabWebSocketClient.cs @@ -301,6 +301,10 @@ namespace WefLab private string userIdx = ""; // Will be extracted from page (shared by every socket) private bool isExtracting = false; + // One-time init guard: the page/config extraction runs only on the first enable; + // later enables (after a disable) just re-open the already-built connections. + private bool initialized = false; + // Duplicate-donation guard: signature -> last seen Time.time private readonly Dictionary recentDonations = new Dictionary(); @@ -311,10 +315,44 @@ namespace WefLab private Queue mainThreadActions = new Queue(); private object actionLock = new object(); - void Start() + void OnEnable() { - // Extract user idx from page URL and then connect - StartCoroutine(ExtractUserIdxAndConnect()); + if (!initialized) + { + // First activation: extract user idx + config from the page, then connect. + initialized = true; + StartCoroutine(ExtractUserIdxAndConnect()); + } + else + { + // Re-enabled after a disable: connections/settings are already built, + // so just re-open the sockets. The keepalive + queue processor restart + // themselves once the sockets reconnect (HandleSocketConnect). + Debug.Log("[WefLab] Re-enabled - reconnecting sockets"); + ConnectAll(); + } + } + + void OnDisable() + { + // OnDestroy is NOT called on SetActive(false), so close the sockets here - + // otherwise the background WebSocket threads keep running while disabled. + Disconnect(); + + // Unity auto-stops this component's coroutines on disable. Reset the queue + // state they leave behind so processing restarts cleanly on re-enable + // (otherwise isProcessingQueue can stay true and stall the queue forever). + donationQueue.Clear(); + queueCount = 0; + isProcessingQueue = false; + queueProcessorCoroutine = null; + + // Drop any background-thread messages queued but not yet drained by Update(), + // so re-enabling doesn't flood Update() with stale alerts. + lock (actionLock) + { + mainThreadActions.Clear(); + } } void Update()