This project introduces a caching system for WaitForSeconds in Unity to optimize the creation of identical timers and a debug view for monitoring cached timers in the Unity Editor.
The WaitForSecondsCache class provides a simple and efficient caching mechanism for WaitForSeconds objects. This reduces memory allocation overhead and improves performance, especially in projects where timers with identical durations are used frequently.
The WaitForSecondsDebugView is a utility designed to help developers monitor and debug cached timers during development.
- Efficient caching: Avoids redundant creation of
WaitForSecondsobjects. - Debugging support: View and monitor cached timers in the Unity Editor.
- Singleton design: The
WaitForSecondsDebugViewleverages aMonoSingletonimplementation for centralized management. - Editor-only Debugging: The debug view is included only when the project is running in the Unity Editor.
To retrieve or cache a WaitForSeconds object:
WaitForSeconds wait = WaitForSecondsCache.Get(0.5f);
yield return wait;To clear all cached timers:
WaitForSecondsCache.Reset();To get a read-only view of the current cache:
var cache = WaitForSecondsCache.GetCache();
foreach (var entry in cache)
{
Debug.Log($"Time: {entry.Key}, WaitForSeconds: {entry.Value}");
}The WaitForSecondsDebugView provides a GUI for monitoring cached timers in the Unity Editor.
- Displays all currently cached
WaitForSecondsobjects. - Allows enabling/disabling the debug view via an Inspector toggle.
The debug view appears in the top-left corner of the game view when running in the Editor:
WaitForSeconds Cache Debug View:
Time: 0.5 seconds
Time: 1.0 seconds
Time: 2.0 seconds
You can enable or disable the debug view using the enableDebugView checkbox in the WaitForSecondsDebugView component.
- MonoSingleton: The
WaitForSecondsDebugViewrelies on a generic MonoSingleton implementation, which can be found here.
To integrate the MonoSingleton, ensure the following class is available in your project:
namespace AbyssMoth.Internal.Codebase.Runtime._MainMenuModule.User
{
public abstract class MonoSingleton<TComponent> : MonoBehaviour where TComponent : Component
{
// Implementation here (already included in the project).
}
}- Add the
WaitForSecondsCacheandWaitForSecondsDebugViewclasses to your project. - Ensure the
MonoSingletonimplementation is present in your codebase. - Add the
WaitForSecondsDebugViewto a GameObject in your scene or let it auto-instantiate.
Contributions are welcome! If you find a bug or have a suggestion, feel free to open an issue or a pull request.
For questions, contact me:
- Email: rimuru.dev@gmail.com
- LinkedIn: Rimuru's Profile
- GitHub: Rimuru's GitHub
License: Open Source, available under the MIT License.