Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Storing a my data file into iOS.

Discussion in 'Getting Started' started by Lenvanthis012, May 20, 2015.

  1. Lenvanthis012

    Lenvanthis012

    Joined:
    Aug 24, 2013
    Posts:
    21
    I want to include a data file in my app bundle so that I don't have to hard-code the data into my program.
    In PC, it is easy and works great. But when I export it to iOS.
    It crashes since in the data path, the file doesn't exist.

    I want to use "Application.dataPath" or "Application.persistentDataPath".
    Something like "Application.dataPath/my_data_file" but
    I don't know how I can put my_data_file into that directory,
    when I export my game into iOS.

    Please somebody enlighten me.

    Thanks.
     
  2. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    You can create a binary file in a Resources folder that Unity will include into your assets and then you can use the asset like:

    For example a binary file in Assets/Resources/myBinaryFile.bytes (yes call it .bytes for this to work) then:

    TextAsset asset = Resources.Load ("myBinaryFile") as TextAsset;

    Then use asset.bytes and asset.bytes.length etc as you see fit. Note, no file extension is given to the Resources.Load() call. It's confusing that it's referring to a TextAsset, but this works fine I use it on all platforms.

    You can do the same with text files also, except you'd use asset.text instead of asset.bytes.
     
    NomadKing likes this.
  3. Lenvanthis012

    Lenvanthis012

    Joined:
    Aug 24, 2013
    Posts:
    21
    larku,

    You saved my day. It works! Thank you so much!
    Following is what I did in detail.

    if ( Debug.isDebugBuild ) {
    Debug.Log(Application.dataPath+"/Resources/my_data_file.bytes");
    }
    TextAsset textAsset = Resources.Load ("my_data_file") asTextAsset;
    byte[] file = textAsset.bytes;

    Thanks again.
     
  4. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    You're welcome.