PS:博主在上编文章中写道webgl读取本地文件数据以及内部网络请求,在这里详细补充一下
首先上一编博主运行html之后报的错误:提示内存不足!!!!
1.首先排查一下webgl包的大小,不能超过2G。
2.F12查看具体错误,在这里博主的是:
a:本地读取StreamingAssets里的配置文件,序列化失败。
b:网络请求方法不能使用JsonConvert.SerializeObject将对象重新序列化,WebGL仅仅支持Unity自身的序列化,不支持外部的其他序列化方式。
PS:1.webgl不支持IO
2.webgl不能直接使用unity的StreamingAssets读取方式
PS:如果小伙伴报的错误如下文章中所示,别急,博主下方会详细说一下解决方案。(7条消息) WebGL谷歌提示内存不够(RuntimeError:memory access out of bounds,火狐提示索引超出界限(RuntimeError:index out of bounds)_先生沉默先的博客-CSDN博客
下面以项目为例,详细讲述打包WEBGL后读取本地文件数据+网络请求:
1.创建unity项目
2.将网络方法RestClient和视频播放器AVPro导入项目,后面博主会附上源码;
3.创建配置文件,可以是txt json等,在这里博主使用的json,
4.创建Canvas空物体,添加mediaplayer组件,路径选择“Path”,“AbsolutePathOrURL”(ps:详细播放m3u8视频流请参考博主这边文章Unity_Webgl: unity+webgl+m3u8+读取streamingAssets里的配置文件 (gitee.com)
http://t.csdn.cn/OwKcGhttp://t.csdn.cn/OwKcG)
5.创建脚本DataBase.cs用来反序列化配置文件的数据,
PS:在这里博主踩了一个雷,就是声明数据变量时用{get;set;}但是{get;set;}在这里不能使用,因为“貌似是.net里面的”(小伙伴可以搜搜查查,奈何博主不会啊-_-;)
using System;
using UnityEngine;
[Serializable]
public class DataBase
{
public override string ToString()
{
return JsonUtility.ToJson(this, true);
}
}
/// <summary>
/// 数据壳
/// </summary>
[Serializable]
public class DataShells<T> : DataBase where T : DataBase
{
public int code;
public string msg;
public T[] data;
}
/// <summary>
/// 数据壳
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
public class DataShell<T> : DataBase where T : DataBase
{
public T data;
public int errorcode;
public string msg;
public int ret;
}
/// <summary>
/// 数据壳
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
public class DatasShell<T> : DataBase where T : DataBase
{
public T[] data;
public int errorcode;
public string msg;
public int ret;
}
/// <summary>
/// 配置文件数据类型
/// </summary>
[Serializable]
public class ConfigURLData : DataBase
{
/// <summary>
/// url
/// </summary>
public string url1;
//public string url1{get;set;}//这个会报空,不建议使用
}
6.现在开始读取配置文件,并播放m3u8格式的视频流,直接上代码,脚本随意挂,在这里我直接挂在相机上了
using System.IO;
using Proyecto26;
using RenderHeads.Media.AVProVideo;
using UnityEngine;
public class MainManager : MonoBehaviour
{
public MediaPlayer player;
void Awake()
{
string path = Path.Combine(Application.streamingAssetsPath, "configURL.json");
RestClient.Request(new RequestHelper
{
Method = "GET",
Uri = path,
}).Then(mresponse =>
{
DataShell<ConfigURLData> configURL = JsonUtility.FromJson<DataShell<ConfigURLData>>(mresponse.Text);
player.OpenMedia(MediaPathType.AbsolutePathOrURL, configURL.data.url1);
}).Catch(err => { Debug.LogError("--------------" + err.Message); });
}
}
7.源码链接:Unity_Webgl: unity+webgl+m3u8+读取streamingAssets里的配置文件链接:https://pan.baidu.com/s/1hCAWxyLbgL4iC4gWAxO7ZQ
提取码:1234
--来自百度网盘超级会员V5的分享
PS:webgl的兼容真的很坑!!!
按照博主的方法做,你一定会成功,不会的可以给博主私信,博主看到会回复