Unity WebGL环境下StreamingAssets文件操作

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

Unity WebGL环境下StreamingAssets文件操作

一、技术背景

在WebGL平台中,由于浏览器的安全沙箱限制:

  1. 传统System.IO文件操作接口不可用
  2. 所有资源访问必须通过HTTP请求实现
  3. 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);
}

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值