Search code examples
c#androidunity-game-enginedaydream

Why is platform dependent compilation not working?


I'm creating a game for Google Daydream (mobile VR platform) and I use different code to load and save data in editor and in target build. My save function looks like this:

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
}

When I run it in the editor I get logs both for android and editor so both parts are executed. Can this be due to Unity emulating a smartphone(every time I play the game in editor I get this warning: "VRDevice daydream not supported in Editor Mode. Please run on target device."?


Solution

  • When you are in Editor you are also in a specific platform, the one chosen in the build settings.

    If you want to run android when not in Editor then you need to say it:

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