System Timer main thread
I am using a Timer (System.Timers.Timer) to countdown to an action which should call a static method from another class. My code is the following:
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += this.OnTimedEvent ;
timer.Enabled = true;
private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
ApplicationModel.SaveLifeNumber (1);
}
In ApplicationModel my code is:
public static void SaveLifeNumber(int life)
{
currrentLives = currrentLives + life;
PlayerPrefs.SetString("currentLives", currrentLives.ToString());
}
My error is:
TrySetSetString can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
I know that System.Timers.Timer calls the OnTimedEvent on a non-UI thread but i was not able to find a way to do it on the main thread.
I tried using
aTimer.SynchronizingObject = SyncGameObject;
but i don't know where to get a SyncronizingObject that will work without an error.
I can't use Windows.Form for a timer because my app will be on mobile.
Your answer
Follow this Question
Related Questions
Best way to get code to run at very precise timing? 0 Answers
Getting a timer to go to 0 1 Answer
Capture Zone Timer 0 Answers
How do I add my Timer to my Score system in C# ? 0 Answers
Countdown timer... 2 Answers