A simple way to create game controllers/managers with global access using Scriptable Objects
Table of Contents
The BaseController<T>
class provides a base for creating global controllers using ScriptableObject. It ensures that only one instance of the controller is created and globally accessible through the Instance property. The asset path of the controller must be specified by subclasses through the abstract GetPath()
method, and the protected OnLoad()
method can be overridden for specific initializations when the controller is loaded.
To get a local copy up and running follow these simple example steps.
- Download or fork this project
- Move the content to your Unity project (if preferred, only the Scripts folder is necessary)
Create a new script that inherits from BaseController<T>
. Example:
- Create a global float variables script
LogsController.cs
using System; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Controllers/Logs Controller", fileName = "LogsController")] public class LogsController : BaseController<LogsController> { public enum ELogType { Normal, Warning, Error } private static readonly Dictionary<ELogType, Action<string>> LogActions = new() { { ELogType.Normal, Debug.Log }, { ELogType.Warning, Debug.LogWarning }, { ELogType.Error, Debug.LogError } }; public void Log(string message, ELogType type) { if (LogActions.TryGetValue(type, out var logAction)) { logAction(message); } else { Debug.LogError($"Log type {type} not supported."); } } protected override string GetPath() => "Controllers/LogsController"; }
- Create an instance of the controller by right-clicking on the desired folder in the Project tab window and choosing the option (in this example)
Create > Controllers > LogsController
- Give your new controller a name, for example,
LogsController
- Now, to access the LogController, simply invoke it using the static call
LogsController.Instance
. Example:LogsController.Instance.Log("[TestLogsController] Normal log message", LogsController.ELogType.Normal);
LuizThiago - @CodeLuiz - [email protected]
Project Link: https://github.com/LuizThiago/GameControllers