LoginSignup
2
2

More than 5 years have passed since last update.

UnityでStreamingAssetsにあるXMLを読み込む方法(UnityEditor, iOS, Androidでの各方法)

Last updated at Posted at 2019-02-15

Unityバージョン

この記事ではnity2018.3.5.f1を使用しています。

StreamingAssetsとは

Unity Editorで Assets/StreamingAssets に配置したアセットのことです。
StreamingAssetsはビルド先のプラットフォームの、特定のフォルダーにそのまま何も変換されない状態で保持されます。
実機でXMLファイルを読み込んでXmlSerializerなどでデシリアライズする場合は、XMLファイルを Assets/StreamingAssets に配置してビルドする必要があります。

各プラットフォームでのStreamingAssetsのパス

Application.streamingAssetsPath をそのまま使用すればOK

ファイルを開いてXMLをデシリアライズする方法

Unity EditorとiOSは通常のファイルアクセスでファイルを取得できますが、Androidはファイルは圧縮された .jar ファイルになっているためUnityのWWWクラスを使う必要があります。
Android以外の場合に通常のファイルアクセスを行っていますが、File.OpenRead を使用しているのがポイントです。
var fs = new System.IO.FileStream(streamingPath, System.IO.FileMode.Open)を使用するとiOSではUnauthorizedAccessExceptionが発生してしまいます。このメソッドではReadだけではなくWrite権限も要求してしまっているためです。
ただし、これはアクセスモードを指定することで回避ができるので File.OpenRead の代わりに以下を用いることもできます。
var fs = new System.IO.FileStream(streamingPath, System.IO.FileMode.Open, FileAccess.Read)

  private HogeXmlData GetSerializedXmlHoge(string path)
    {
        var streamingPath= System.IO.Path.Combine(Application.streamingAssetsPath, path)
        HogeXmlData hoge = null;

#if UNITY_ANDROID && !UNITY_EDITOR
        //wwwを使用する方法
        WWW www = new WWW(streamingPath);
        while (!www.isDone) { }
        using (var sr = new StringReader(www.text))
        {
            hoge = (HogeXmlData) serializer.Deserialize(sr);
        }       
#else 
        //通常のファイルアクセス
        using (var fs = File.OpenRead(streamingPath))
        {
            hoge = (HogeXmlData) serializer.Deserialize(fs);
        }
#endif
        return hoge ;
    }

その他

WWWでファイルのパスを間違えた場合、www.textが空文字列となり、XmlException: Document element did not appear. Line 1, position 1. のエラーが出ますので、そのときはパスが間違っていないか確認すると良いです。
上記のようにStreamingAssetsは少なくともiOSではWrite権限を使用できないため、書き込む場合はApplication.persistentDataPathを使用しましょう。

参考にさせていただいたURL

https://qiita.com/tetsujp84/items/37a44da7d5b9c890fc1d
https://forum.unity.com/threads/accessing-files-in-streamingassets-on-ios-access-denied.261994/

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2