You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity Android构建时WebClient读取服务器TXT文件失败的问题解决

Unity Android打包后无法读取服务器TXT文件的问题与解决

问题详情

  • 需求:读取服务器上的TXT文件(示例地址:https://example-files.online-convert.com/document/txt/example.txt)
  • 异常现象:Unity编辑器内运行功能正常,打包为Android安装包后抛出异常,屏幕显示An exception occured during a WebClient request
  • 已配置操作:将Player Settings中相关设置改为"required"
  • 实现方式:ShowingTheTextFromASevrer脚本挂载在主相机上,关联屏幕上的TextMeshProUGUI组件;该脚本继承自抽象类GettingTextFromAServer

相关脚本代码

抽象类GettingTextFromAServer

using System.Net;
using System.IO;
using UnityEngine;

public abstract class GettingTextFromAServer : MonoBehaviour
{
    public string GetTheTextFromAServer(string url)
    {
        WebClient client = new WebClient();
        Stream stream = client.OpenRead(url);
        StreamReader reader = new StreamReader(stream);
        return reader.ReadToEnd();
    }
}

实现类ShowingTheTextFromASevrer

using UnityEngine;
using TMPro;

public class ShowingTheTextFromASevrer : GettingTextFromAServer
{
    [SerializeField] private TextMeshProUGUI TextOnTheScreen;

    private void Start()
    {
        TextOnTheScreen.text = "";
        string TextFromTheServer;
        try
        {
            TextFromTheServer = GetTheTextFromAServer("https://example-files.online-convert.com/document/txt/example.txt");
            Debug.Log(TextFromTheServer);
            TextOnTheScreen.text += TextFromTheServer;
        }
        catch (System.Exception AnyException)
        {
            TextOnTheScreen.text += AnyException.Message;
        }
    }
}

权限配置疑问

猜测异常原因可能是AndroidManifest.xml缺少权限,当前清单内容如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
    xmlns:tools="http://schemas.android.com/tools">
    <application>
        <activity android:name="com.unity3d.player.UnityPlayerActivity"
                  android:theme="@style/UnityThemeSelector">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>
    </application>
</manifest>

询问以下权限配置应该放置在何处:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

最终解决方法

  1. 在AndroidManifest.xml的<application>标签上方添加权限配置:
<permission android:name="android.permission.INTERNET"/>
<permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  1. 应用需要使用密钥签名(类似发布至Google Play商店时的签名操作)才能正常运行。

内容的提问来源于stack exchange,提问作者user20311258

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:00:55