Unity同步加载Android里的StreamingAssets里的文件
16lz
2022-04-22
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大门(Gallery拖动相片特效)
- android 网络图片与网页读取
- Android(安卓)File 数据存储
- Android(安卓)Log Analysis
- android 图片压缩
- 任务栏一键删除 Recent APP
- Android(安卓)Log Analysis bugreport
- Android手机开发:ImageView使用和从内存读取图片显示
- Android读取联系人的姓名及号码