Unity WebGL环境下StreamingAssets文件操作

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);
}
要在Unity WebGL中通过StreamingAssets方式播放MP4视频,可以通过以下步骤进行操作: 1. 将MP4视频文件放入Unity项目的StreamingAssets文件夹中(如果没有该文件夹,需要手动创建)。 2. 在Unity场景中创建一个UI按钮,添加一个Button组件。 3. 在Button组件的OnClick事件中添加一个新的函数。 4. 在该函数中,使用Unity的WWW类加载MP4视频文件,并将其作为纹理显示在场景中的一个RawImage组件上。 下面是一个示例代码: ```c# using UnityEngine; using UnityEngine.UI; using System.Collections; public class VideoPlayer : MonoBehaviour { public RawImage rawImage; public Button playButton; private string videoURL; private bool isPlaying = false; private MovieTexture movieTexture; void Start () { videoURL = Application.streamingAssetsPath + "/video.mp4"; playButton.onClick.AddListener(OnClickPlayButton); } void OnClickPlayButton() { if (!isPlaying) { StartCoroutine(PlayVideo()); } } IEnumerator PlayVideo() { isPlaying = true; Handheld.PlayFullScreenMovie(videoURL, Color.black, FullScreenMovieControlMode.Hidden, FullScreenMovieScalingMode.Fill); yield return new WaitForEndOfFrame(); isPlaying = false; } } ``` 在上面的代码中,我们通过Unity的Handheld类来播放MP4视频,而不是使用WebGL的HTML5 video标签。这是因为UnityWebGL支持并不完全,不支持所有HTML5标签和功能。此外,我们还使用了Unity的RawImage组件来显示视频,而不是使用HTML5 video标签的默认控件。 请注意,由于浏览器的限制,我们无法在Unity WebGL中直接从本地文件系统中加载MP4视频,因此我们需要将其放入StreamingAssets文件夹中并使用Unity的Handheld类进行播放。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值