UnityはAndroidのStreamingAssetsのファイルを同期してロードします
3452 ワード
AssetBundle.LoadFromFile
JavaでJarパッケージを作成してPlugins/Androidディレクトリの下に読み込む
Unityツールクラス
スクリプトのテスト
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
}
}