unity使用文件流读取streamingassets下的资源

目的:读取streamingassets下的文件中指定的一段字节

已知:文件中的起始位置,和需要读取的长度

1.android下读取

1.1 不能直接使用C#的FileStream,读取失败

var buffer = new byte[size];
FileStream stream = File.OpenRead(path);
stream.Read(buffer , pos, size);

报错:IsolatedStorageException: Could not find a part of the path "/jar:file:/data/app/com.xxx.xxxx-1/base.apk!/assets/xxx.pack".

 

1.2 可以使用Unity原生接口与Android交互

主要过程:

Java

public class XXXPlugin extends UnityPlayerNativeActivity {
    protected AssetManager assetManager;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		assetManager = getAssets();
    }

	//返回字节数组
	public byte[] LoadBytes(String path,int offset,int len)
	{
         //可以缓存起来,不需每次都open
         Inp
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity中,可以使用以下方法来加载StreamingAssets文件夹下的文件: 1. 使用WWW类加载。代码示例: ``` string filePath = Application.streamingAssetsPath + "/example.txt"; WWW www = new WWW(filePath); yield return www; string text = www.text; ``` 上述代码中,filePath表示需要加载的文件路径,在该路径后面添加文件名即可加载指定的文件。注意,需要使用WWW类来加载资源,加载完成后,可以通过www.text等属性获取资源内容。 2. 使用File类读取。代码示例: ``` string filePath = Application.streamingAssetsPath + "/example.txt"; StreamReader reader = new StreamReader(filePath); string text = reader.ReadToEnd(); reader.Close(); ``` 上述代码中,filePath表示需要读取文件路径,在该路径后面添加文件名即可读取指定的文件使用StreamReader类可以读取文件内容,最后需要关闭StreamReader对象。 需要注意的是,对于Android平台和iOS平台,StreamingAssets文件夹下的文件在打包后会被压缩到APK或IPA包中,无法直接访问。在这种情况下,需要将文件先复制到Application.persistentDataPath路径下,然后再进行读取操作。可以使用以下代码来实现: ``` IEnumerator CopyFile() { string filePath = ""; // Android平台 if (Application.platform == RuntimePlatform.Android) { filePath = "jar:file://" + Application.dataPath + "!/assets/example.txt"; } // iOS平台 else if (Application.platform == RuntimePlatform.IPhonePlayer) { filePath = Application.dataPath + "/Raw/example.txt"; } // 其他平台 else { filePath = "file://" + Application.streamingAssetsPath + "/example.txt"; } WWW www = new WWW(filePath); yield return www; string targetPath = Application.persistentDataPath + "/example.txt"; File.WriteAllBytes(targetPath, www.bytes); } ``` 上述代码中,首先判断当前平台,然后根据平台不同设置不同的文件路径。使用WWW类加载文件,并将文件复制到Application.persistentDataPath路径下,最后可以使用File类进行读取操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值