Unity交叉推广按钮打开原始文本文件而非跳转Google Play链接
Unity交叉推广按钮打开文本文件而非Google Play链接的解决方案
我在开发Unity项目时做了一个交叉推广按钮,原本应该跳转至Google Play应用链接,但点击后打开的却是GitHub/GDrive上托管的原始文本文件,而非目标链接。试过换托管平台、URL缩短和重定向都没用,当前使用的简化脚本如下:
using System.Collections; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class crospromo : MonoBehaviour { public string imageURL; public string linkURL; private Image image; private void Start() { image = GetComponent<Image>(); StartCoroutine(LoadImage()); } private IEnumerator LoadImage() { using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageURL)) { yield return www.SendWebRequest(); if (!www.isNetworkError && !www.isHttpError) { Texture2D texture = DownloadHandlerTexture.GetContent(www); if (texture != null) { Sprite sprite = Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f)); image.sprite = sprite; } } } } public void OnClick() { Application.OpenURL(linkURL); } }
问题根源
当前脚本的OnClick()方法直接调用Application.OpenURL(linkURL),如果linkURL填的是文本文件的托管地址,Unity会直接打开这个文件的网页,不会自动读取文件内的链接内容。你需要先通过网络请求获取文本文件里的Google Play链接,再调用跳转方法。
修改后的解决方案
修改脚本,添加读取文本内容的逻辑,替换原OnClick()方法:
using System.Collections; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class crospromo : MonoBehaviour { public string imageURL; public string linkTextFileURL; // 明确指向托管的文本文件地址 private Image image; private void Start() { image = GetComponent<Image>(); StartCoroutine(LoadImage()); } private IEnumerator LoadImage() { using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageURL)) { yield return www.SendWebRequest(); if (!www.isNetworkError && !www.isHttpError) { Texture2D texture = DownloadHandlerTexture.GetContent(www); if (texture != null) { Sprite sprite = Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f)); image.sprite = sprite; } } } } public void OnClick() { StartCoroutine(LoadAndOpenLink()); } private IEnumerator LoadAndOpenLink() { using (UnityWebRequest www = UnityWebRequest.Get(linkTextFileURL)) { yield return www.SendWebRequest(); if (!www.isNetworkError && !www.isHttpError) { // 去除文本首尾空白字符,避免换行/空格干扰 string targetLink = www.downloadHandler.text.Trim(); if (!string.IsNullOrEmpty(targetLink)) { Application.OpenURL(targetLink); } else { Debug.LogError("文本文件中未找到有效链接"); } } else { Debug.LogError("加载链接失败: " + www.error); } } } }
关键修改说明
- 将原
linkURL重命名为linkTextFileURL,明确其指向托管的文本文件地址 - 新增
LoadAndOpenLink()协程,通过UnityWebRequest.Get()读取文本文件内容 - 对读取到的文本做
Trim()处理,移除可能存在的换行、空格等无效字符 - 验证链接有效性后再调用
Application.OpenURL(),避免无效跳转
注意事项
- 确保托管的文本文件只包含纯Google Play链接,无多余文字、换行或空格
- Android平台需确认已添加网络权限:Unity通常会自动生成
<uses-permission android:name="android.permission.INTERNET" />,可手动检查AndroidManifest.xml - Google Play链接建议使用官方格式:
market://details?id=com.your.app.id(Android直接打开应用商店)或https://play.google.com/store/apps/details?id=com.your.app.id(兼容多平台) - 脚本已添加错误日志,方便调试网络请求失败的场景
内容的提问来源于stack exchange,提问作者stylobic
相关产品推荐
相关产品推荐

