Unity Streaming Assets资源读取

Unity在读取StreamingAssets下的资源IOS / Android平台有差异。

  path = Application.streamingAssetspath + resource_path;

其中:

  byte[] bytes = File.ReadAllBytes(path);
  var assetBundle = AssetBundle.CreateFromMemoryImmediate(bytes);
  //TODO assetBundle
  using(var www = new WWW(path)){
    yield return www;
    if (www.isDone && string.IsNullOrEmpty(www.error)) {
      //TODO www.assetBundle
    }
  }
   byte[] readTextByBytes(InputStream inputStream) {
     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

     try {
       byte buff[] = new byte[1024];
       int len;

       while ((len = inputStream.read(buf)) != -1) {
          outputStream.write(buf, 0, len);
       }

       inputStream.close();
       outputStream.close();
     } catch(IOException e) {
       //TODO log
     }
   }

   //因为Android下不能通过File读取StreamAssets下的资源,所以需要通过java层同步读取assets bundle
   InputStream fileStream = getAssets().open(resource_path);
   readTextByBytes(fileStream);   

或者

  IEnumerable<AssetBundle> WWWEnumerable(string path) {
    using (var www = new WWW(path)) {
      yield return www.assetBundle;
      www.assetBundle.Unload(false);
    }
  }
  foreach (var assetBundle in WWWEnumerable(path)) {
     result = assetBundle;
  }
  //这里需要 APK Expansion Zip Library

  //这里需要在资源名前增加 "assets/" 
  pathToFileInsideZip = "asssets/" + resource_path;

  ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(appContext, mainVersion, patchVersion);
  InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
  readTextByBytes(fileStream);  
  string path;
  if (Application.platform == RuntimePlatform.Android) {
    path = Application.dataPath + "!assets/" + resource_path;
  }
  else {
    path = Application.streamingAssetsPath + "/" + resource_path;
  }
  AssetBundle assetbundle = AssetBundle.LoadFromFile(path);

注意点:

aliyun