GetInt 只能从主线程调用

GetInt can only be called from the main thread

我正在做载具游戏。我这样写 BaseVehicle class;

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 can only be called from the main thread.").

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.
    }
}

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

您正在 MonoBehavior (private BaseVehicle car = new Car();) 的字段声明中调用 PlayerPref.GetInt。这个时候,团结的"normal execution"还没有开始

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

我的建议是:

private BaseVehicle car;

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

这可能有效。