为什么依赖于平台的编译不起作用?

Why is platform dependent compilation not working?

我正在为 Google Daydream(移动 VR 平台)创建游戏,我使用不同的代码在编辑器和目标构建中加载和保存数据。我的保存功能如下所示:

public void SaveData() {
    XmlSerializer serializer = new XmlSerializer(typeof(ItemDatabase));
    FileStream stream;
#if UNITY_ANDROID
    stream = new FileStream(Application.persistentDataPath + "/game_data.xml", FileMode.Create);
    serializer.Serialize(stream, gameDB);
    stream.Close();
    Debug.Log("Data Saved[Android]");
#endif
#if UNITY_EDITOR
    stream = new FileStream(Application.dataPath + "/StreamingAssets/XML/game_data.xml" , FileMode.Create);
    serializer.Serialize(stream, gameDB);
    stream.Close();
    Debug.Log("Data Saved[Editor]");
#endif
}

当我在编辑器中 运行 它时,我得到了 android 和编辑器的日志,所以这两个部分都被执行了。这可能是由于 Unity 模拟了智能手机(每次我在编辑器中玩游戏时都会收到此警告:"VRDevice daydream not supported in Editor Mode. Please run on target device."?

当您在编辑器中时,您也在特定平台中,即在构建设置中选择的平台。

如果你想 运行 android 当不在编辑器中时,你需要说出来:

#if UNITY_ANDROID && !UNITY_EDITOR
    stream = new FileStream(Application.persistentDataPath + "/game_data.xml", FileMode.Create);
    serializer.Serialize(stream, gameDB);
    stream.Close();
    Debug.Log("Data Saved[Android]");
#elif UNITY_EDITOR
    stream = new FileStream(Application.dataPath + "/StreamingAssets/XML/game_data.xml" , FileMode.Create);
    serializer.Serialize(stream, gameDB);
    stream.Close();
    Debug.Log("Data Saved[Editor]");
#endif
}