When trying to access a gameobjects position from a timer like this:
public static void Start()
{
if(!timerStarted)
{
timerStarted = true;
timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += CheckEarnings;
timer.AutoReset = true;
timer.Enabled = true;
}
}
private static void CheckEarnings(object sender, ElapsedEventArgs e)
{
foreach (BuildingData building in BuildingRegistry.registeredBuildings)
{
MonoBehaviour.print(building.attachedGameObject.transform.position);
}
}
(In a Static Class if this makes any difference)
...The following Error is thrown:
get_transform 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. UnityEngine.GameObject:get_transform() PlayerManagement:CheckEarnings(Object, ElapsedEventArgs) (at Assets/Scripts/PlayerManagement.cs:53) System.Timers.Timer:Callback(Object)
For me it looks like there is another thread created for the timer which can't access the main thread. How can I solve this problem?
You're correct in assuming that the issue is the timer is running on a seperate thread, that said there are many different solutions to this. I assume based on your syntax that you are using System.Timers.Timer, this in your instance means that the timer runs the elapsed event on a ThreadPool.
If you are intent on using the C# timers rather than creating your own timer using Time.deltaTime then the issue becomes how to use the UnityAPI on a seperate thread, the simple truth is that you can't. Unity is thread safe by design and thus you must create a system for running functions on the main thread by creating a list of Delegates and then on the main thread running through that list executing them all.
The simplest solution though would be to simply store a float value of total time elapsed and every frame increase it by Time.deltaTime, the float value will represent the seconds passed and you can quite easily call functions based on that value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With