Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."?

like image 575
Wojtek Wencel Avatar asked Sep 15 '17 18:09

Wojtek Wencel


People also ask

What is Unity_android?

A Unity ID allows you to buy and/or subscribe to Unity products and services, shop in the Asset Store and participate in the Unity community. Unity Forum.

What is #if Unity_editor?

Using #if UNITY_EDITOR will actually run the code, only in the editor, by that it means both edit and play mode. The code inside the block, won't be included in the build - that's what I understood. I'm gonna try and build my game, and see if I get anything from inside those blocks... -1.

Is unity independent platform?

Unity includes a feature called Platform Dependent Compilation. This consists of some preprocessor directives that let you partition your scripts to compile and execute a section of code exclusively for one of the supported platforms.


1 Answers

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
}
like image 170
Everts Avatar answered Nov 01 '22 05:11

Everts