Unity WebGL环境下StreamingAssets文件操作
一、技术背景
在WebGL平台中,由于浏览器的安全沙箱限制:
- 传统System.IO文件操作接口不可用
- 所有资源访问必须通过HTTP请求实现
- StreamingAssets路径映射规则改变:
| 平台 | 路径格式 | |--------|-------------------------| | Editor | file://PATH_TO_PROJECT | | WebGL | http://HOSTING_DOMAIN/ |
二、文本文件读取方案
1. 核心实现模块
public class WebFileReader : SingletonMono<WebFileReader>
{
public void ReadTextFile(string relativePath, Action<string> callback)
{
StartCoroutine(ReadTextCoroutine(relativePath, callback));
}
private IEnumerator ReadTextCoroutine(string relativePath, Action<string> callback)
{
/*
Uri upLinkConfig = new System.Uri(Path.Combine(
Application.streamingAssetsPath + @"/UPLinkProject/index.html", ""));
*/
string fullPath = Path.Combine(
Application.streamingAssetsPath,
relativePath.TrimStart('/'));
UnityWebRequest request = UnityWebRequest.Get(fullPath);
yield return request.SendWebRequest();
if(request.result == UnityWebRequest.Result.Success)
{
callback?.Invoke(request.downloadHandler.text);
}
else
{
Debug.LogError($"文件读取失败: {fullPath}\n错误信息: {request.error}");
callback?.Invoke(null);
}
}
}
2. 使用示例
// 配置文件读取
void LoadServiceConfig()
{
WebFileReader.Instance.ReadTextFile("Config/serverconfig.json", (json) =>
{
if(!string.IsNullOrEmpty(json))
{
serviceConfig = JsonUtility.FromJson<ServiceConfig>(json);
Debug.Log($"服务器地址: {serviceConfig.apiEndpoint}");
}
else
{
Debug.LogWarning("使用默认配置文件");
serviceConfig = GetDefaultConfig();
}
});
}
三、HTML文件访问方案
1. 路径构建规范
public class WebUrlBuilder
{
public static string BuildHtmlPath(string relativePath)
{
return Path.Combine(Application.streamingAssetsPath, relativePath)
.Replace("\\", "/") // 统一路径格式
.TrimEnd('/'); // 移除末尾分隔符
}
}
2. 参数化URL调用
[Serializable]
public class UserData
{
public string userId;
public string sessionToken;
}
void OpenWebDashboard(UserData user)
{
string baseUrl = WebUrlBuilder.BuildHtmlPath("Dashboard/index.html");
// 使用WWW.EscapeURL处理特殊字符
string parameters = $"?userId={WWW.EscapeURL(user.userId)}" +
$"&token={WWW.EscapeURL(user.sessionToken)}";
Application.OpenURL(baseUrl + parameters);
}