I have the below code, when i dispose the aTimer i expect the refference to be null but it says its not.
How can i make sure the aTimer is not there anymore?
using UnityEngine;
using System.Timers;
public class CTimer : MonoBehaviour {
private static System.Timers.Timer aTimer;
void Start () {
aTimer = new System.Timers.Timer(2000);
aTimer.Elapsed += new ElapsedEventHandler(OnTick);
aTimer.Start();
}
private static void OnTick(object source, ElapsedEventArgs e) {
print(e.SignalTime);
}
void OnDisable () {
aTimer.Dispose();
print(aTimer == null);
}
}
the only thing that calls the garabage collector is System.GC.Collect();
marking something as null only marks it as no longer used and ready to be collected by the GC, there is no ‘immediate collecting’ (and you don’t want any as it would reduce the performance significantly of managed systems)
Trust me, you don’t want to get into threading then. I believe the functionality you seek can be done with the following code:
using UnityEngine;
using System.Collections;
public class CR_Demo : MonoBehaviour
{
bool run = true;
IEnumerator Start()
{
while (run)
{
yield return new WaitForSeconds(2);
print(Time.time);
}
}
void OnDisable()
{
run = false;
}
}
Okay, i added the yield to the startcoroutine according to documents this is supposed to wait until doalphathing ends. But unity still crashes with an endless loop.
using UnityEngine;
using System.Collections;
public class Corutine : MonoBehaviour {
float alpha = 0;
IEnumerator Start () {
yield return StartCoroutine(DoAlphaThing());
yield return new WaitForSeconds(2f);
Application.LoadLevel(1);
}
IEnumerator DoAlphaThing () {
while (alpha < 255) {
alpha += 0.01f;
if (alpha > 255) break;
print (alpha);
}
yield return new WaitForSeconds(2f);
while (alpha < 255) {
alpha -= 0.01f;
if (alpha < 0) break;
print (alpha);
}
}
}
Neither of those while loops really does anything. You’re just increasing “alpha” from 0 to 255 without waiting, so the effect is the same as if you did “alpha = 255”, except a lot less efficient (and the same going from 255 to 0). You need a yield inside the loops, and you need to use Time.deltaTime rather than an arbitrary number like .01. See Fade.