How do I get a singleton to work after unity hot reloads?
I got a timer manager class that managers all of the timers in my game. It's a singleton and all of my other classes refer to it by it's Instance. But as soon as I do a hot reload, the other classes sees a reloaded instance but I think it's a new instance that the other classes are refering to. Does anyone know how to fix this?
My Code:
//*****************************************************************************
// Timer data class
//*****************************************************************************
[Serializable]
public class Timer
{
public float defaultTime;
public float curTime;
public bool paused;
public bool isDone;
}
//*****************************************************************************
// Timer manager
//*****************************************************************************
public class TimerManager : MonoBehaviour
{
private static TimerManager _instance = null;
[SerializeField]
private List<Timer> timers = new List<Timer>();
// Start is called before the first frame update
void Awake()
{
if (!_instance)
_instance = this;
else
DestroyImmediate(this);
DontDestroyOnLoad(_instance.gameObject);
}
private void OnEnable()
{
if (!_instance)
_instance = (TimerManager)FindObjectOfType<TimerManager>();
}
// Update is called once per frame
void Update()
{
UpdateTimers();
}
private void UpdateTimers()
{
foreach (var timer in timers)
{
// Check if timer can work
if (timer.paused || timer.isDone)
continue;
// Update all timers
timer.curTime -= Time.deltaTime;
if (timer.curTime <= 0f)
{
timer.isDone = true;
timer.paused = true;
timer.curTime = 0f;
}
}
}
// Public Methods
// public static TimerManager Instance => _instance;
public static TimerManager Instance
{
get
{
// if (_instance)
return _instance;
}
}
public Timer GetNewTimer( float seconds = 0f )
{
// TimerData newTimer = new TimerData( seconds );
Timer newTimer = new Timer()
{
defaultTime = seconds,
curTime = seconds,
paused = true,
isDone = false
};
timers.Add( newTimer );
return newTimer;
}
public void Delete( Timer timer )
{
if (timers.Contains( timer ))
timers.Remove( timer );
// timer.Dispose()
// timer = null;
}
public void Go( Timer timer )
{
timer.paused = false;
}
public void Pause( Timer timer )
{
timer.paused = true;
}
public void Set( ref Timer timer, float seconds )
{
// if (!timers.Contains( timer ))
// return;
//
// TimerData reftimer = timers.( timer );
timer.curTime = timer.defaultTime = seconds;
timer.paused = true;
timer.isDone = false;
}
public void Reset( Timer timer )
{
timer.paused = true;
timer.isDone = false;
timer.curTime = timer.defaultTime;
}
}
Comment