【问题标题】:GetInt can only be called from the main threadGetInt 只能从主线程调用
【发布时间】:2015-04-07 20:06:20
【问题描述】:

我正在开发车辆游戏。我是这样写 BaseVehicle 类的;

public class BaseVehicle
{
    private string name;
    private int speed;
    private int level;

    public string Name
    {
        get{return name;}
        set{name = value;}
    }

    public int Speed
    {
        get{return speed;}
        set{speed = value;}
    }

    public int Level
    {
        get{return level;}
        set{level = value;}
    }
}

这运作良好。但是我尝试使用 PlayerPrefs 设置级别值,控制台给出错误(“GetInt 只能从主线程调用。”)。

public class Car : BaseVehicle
{
    public Car()
    {
        Name = "965 Cabriolet";
        Speed = 250;
        Level = PlayerPrefs.GetInt("CarLevel");//There is a error, how can i call PlayerPrefs in to this class.
    }
}

【问题讨论】:

  • 您没有提供足够的详细信息。你是如何实例化这个类的?什么是 PlayerPrefs?您似乎使用它的方式,它看起来像是一个静态类。我说的对吗?
  • PlayerPrefs 是 Unity3d library 类。
  • 我知道如何使用 PlayerPrefs 我在 unityforums 中查看了答案,但我找不到,问题是如何在我的 Car 类中使用它?
  • Car 是 MonoBehaviour 还是 ScriptableObject 的成员?它在哪里实例化?

标签: c# properties unity3d


【解决方案1】:

您的错误是您在主循环正常执行之前调用了PlayerPref.GetInt

您在MonoBehavior (private BaseVehicle car = new Car();) 的字段声明中调用PlayerPref.GetInt。此时,unity的“正常执行”还没有开始。

您只能在 Awake()Start()Update() 等 Unity 事件中调用 PlayerPref.GetInt

我的建议是:

private BaseVehicle car;

void Awake() {
    car = new Car();
}

这可能有效。

【讨论】:

    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2013-04-16
    相关资源
    最近更新 更多