Unity同步加载Android里的StreamingAssets里的文件

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<Sprite>();
        GetComponent<SpriteRenderer>().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<byte[]>("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>().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
    }
	
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Unity加载`StreamingAssets`文件夹中的图片到列表中,你可以使用`System.IO`命名空间和Unity的UI系统。下面是一个示例代码: ```csharp using UnityEngine; using UnityEngine.UI; using System.IO; public class ImageListLoader : MonoBehaviour { public GameObject imagePrefab; // 图片预制体 public Transform content; // 列表的内容容器 private string imagesFolderPath = "Images"; // 图片文件夹路径 private void Start() { LoadImages(); } private void LoadImages() { string streamingPath = Path.Combine(Application.streamingAssetsPath, imagesFolderPath); if (Directory.Exists(streamingPath)) { string[] imageFiles = Directory.GetFiles(streamingPath); foreach (string imagePath in imageFiles) { // 加载图片预制体 GameObject imageGO = Instantiate(imagePrefab, content); // 获取图片名称 string imageName = Path.GetFileNameWithoutExtension(imagePath); // 设置图片预制体的名称 imageGO.name = imageName; // 设置图片显示 Image imageComponent = imageGO.GetComponent<Image>(); StartCoroutine(LoadImageCoroutine(imagePath, imageComponent)); } } } private IEnumerator LoadImageCoroutine(string imagePath, Image imageComponent) { var request = UnityEngine.Networking.UnityWebRequestTexture.GetTexture("file://" + imagePath); yield return request.SendWebRequest(); if (request.result != UnityEngine.Networking.UnityWebRequest.Result.Success) { Debug.LogError("Failed to load image: " + request.error); yield break; } Texture2D texture = ((UnityEngine.Networking.DownloadHandlerTexture)request.downloadHandler).texture; Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f); imageComponent.sprite = sprite; } } ``` 这段代码假设你已经在场景中创建了一个空对象,并将`ImageListLoader`脚本附加到该对象上。你还需要创建一个图片预制体,并将其分配给`imagePrefab`变量。`content`变量引用了列表的内容容器,你可以在Unity编辑器中将容器对象指定为变量。 在`Start`方法中,我们调用`LoadImages`方法来加载图片。`LoadImages`方法首先构造了`StreamingAssets`文件夹中图片的路径,并检查路径是否存在。然后,我们使用`Directory.GetFiles`方法获取图片文件夹中的所有文件路径,并遍历这些文件路径。 在循环中,我们实例化一个图片预制体,并设置预制体的名称为图片名称(去除扩展名)。然后,我们获取预制体上的`Image`组件,并使用协程`LoadImageCoroutine`加载图片并设置到`Image`组件上。 在`LoadImageCoroutine`方法中,我们使用`UnityWebRequestTexture.GetTexture`方法加载图片。通过协程等待加载完成后,我们检查是否成功加载。如果成功加载,我们创建一个`Sprite`并设置到传入的`Image`组件上。 请确保你已经正确设置了场景和图片资源,并根据需要修改代码中的路径和加载的资源类型。同时,需要在列表的内容容器中创建一个空对象作为父级,并将其指定给脚本中的`content`变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值