gpt4 book ai didi

c# - Unity3d 从定时器访问主线程

转载 作者:行者123 更新时间:2023-12-03 13:08:46 33 4
gpt4 key购买 nike

<分区>

当尝试从这样的计时器访问游戏对象位置时:

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);
}
}

(在静态类中,如果这有什么不同的话)

...抛出以下错误:

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)

对我来说,它看起来像是为计时器创建了另一个无法访问主线程的线程。我该如何解决这个问题?

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com