Unity同步加载Android里的StreamingAssets里的文件
16lz
2021-01-23
AssetBundle.LoadFromFile
public class TestAssetBundle : MonoBehaviour {void Start () { string path; if (Application.platform == RuntimePlatform.Android) { path = Application.dataPath + "!assets/Android/hero_20001-assetbundle"; } else { path = Application.streamingAssetsPath + "/IOS/hero_20001-assetbundle"; } AssetBundle assetBundle = AssetBundle.LoadFromFile(path); Sprite[] sprites = assetBundle.LoadAllAssets(); GetComponent().sprite = sprites[0];}}
通过在Java中编写Jar包读取 放到Plugins/Android目录下
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import com.unity3d.player.UnityPlayer;import android.util.Log;public class AssetLoad { private static byte[] readtextbytes(InputStream inputStream) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //长度这里暂时先写成1024 byte buf[] = new byte [1024]; int len; try { while ((len = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, len); } outputStream.close(); inputStream.close(); } catch (IOException e) { } return outputStream.toByteArray();} //读取assetbund并且返回字节数组public static byte[] loadFile(String path){ InputStream inputStream = null ; try { inputStream = UnityPlayer.currentActivity.getAssets().open(path); } catch (IOException e) { Log.e("ihaiu.com", e.getMessage()); } return readtextbytes(inputStream);}}
Unity工具类
using UnityEngine;using System.Collections;public class AndroidAssetLoadSDK { public static byte[] LoadFile(string path) { AndroidJavaClass m_AndroidJavaClass = new AndroidJavaClass("包名"); return m_AndroidJavaClass.CallStatic("loadFile", path); } public static string LoadTextFile(string path) { byte[] bytes = LoadFile(path); if (bytes == null) return "Error bytes=null"; return System.Text.Encoding.UTF8.GetString ( bytes ); } public static AssetBundle LoadAssetBundle(string path) { byte[] bytes = LoadFile(path); if (bytes == null) return null; return AssetBundle.LoadFromMemory(bytes); }}
测试脚本
using UnityEngine;using System.Collections;using System.IO;using UnityEngine.UI;public class TestLoadText : MonoBehaviour{void Start () { Test();} void OnGUI() { if (GUILayout.Button("Test", GUILayout.MinWidth(200), GUILayout.MinHeight(100))) { Test(); } } public void Test() { string path = "game_const.json"; string str = LoadText(path); GetComponent().text = string.IsNullOrEmpty(str) ? "Load Empty" : str; } public string LoadText(string path) { #if UNITY_ANDROID && !UNITY_EDITOR return AndroidAssetLoadSDK.LoadTextFile(path); #else return File.ReadAllText(Application.streamingAssetsPath + "/" + path); #endif }}
更多相关文章
- android 字符串数组资源
- Android jni中数组参数的传递方式
- Android intent 传递数组对象序列化
- android 图片与byte数组间的转换
- android JNI java与C++传递String数组(引用类型)
- 2.Retrofit上传list数组给后端
- 在android中创建包含对象数组对象List 的Parcelable
- android解析二维数组对象key:value
- 【Android学习笔记】AutoCompleteTextView(数组在代码中)