GetInt只能从主线程调用

时间:2015-04-07 03:22:10

标签: c# properties unity3d

我正在开发车辆游戏。我写了这样的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.
    }
}

1 个答案:

答案 0 :(得分:1)

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

您在PlayerPref.GetIntMonoBehavior)的字段声明中呼叫private BaseVehicle car = new Car();。这时,"正常执行"统一尚未开始。

您只能在Unity事件中致电PlayerPref.GetInt,例如Awake()Start()Update()等。

我的建议是:

private BaseVehicle car;

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

这可能有效。