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?