0

对于我的移动 Unity 应用程序,我需要一个 Web 视图元素并使用 UniWebView 插件。如下代码所示,我写了一个脚本来动态加载一个html字符串。在我的应用程序中,包含场景将根据用户交互多次加载。

在编辑器和 iOS 上,它按预期工作。在 Android 上,Web 视图显示为应用程序启动后的第一个场景加载。但是后来的重新加载有时会起作用,有时会任意失败,仅显示白色区域。尽管加载微调器可以工作,但会发生这种情况,因此它似乎只是可视化失败。

脚本附在下面。我将脚本放在一个简单的面板游戏对象上,该对象仅用于定义屏幕区域。

知道如何解决这个问题吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YouTubePlayer : MonoBehaviour
{

    private UniWebView uniWebView;

    public void Start()
    {
        uniWebView = GetComponent<UniWebView>();

        if (uniWebView == null)
        {
            Debug.Log("YOUTUBE PLAYER: Adding uniwebview Component");
            uniWebView = gameObject.AddComponent<UniWebView>();
        }

        uniWebView.OnPageStarted += (view, url) =>
        {
            Debug.Log("YOUTUBE PLAYER: OnPageStarted with url: " + url);
        };
        uniWebView.OnPageFinished += (view, statusCode, url) =>
        {
            Debug.Log("YOUTUBE PLAYER: OnPageFinished with status code: " + statusCode);
        };
        uniWebView.OnPageErrorReceived += (UniWebView webView, int errorCode, string errorMessage) =>
        {
            Debug.Log("YOUTUBE PLAYER: OnPageErrorReceived errCode: " + errorCode
                      + "\n\terrMessage: " + errorMessage);
        };

        uniWebView.SetShowSpinnerWhileLoading(true);
        uniWebView.ReferenceRectTransform =    gameObject.GetComponent<RectTransform>();

        uniWebView.LoadHTMLString(YoutubeHTMLString, "https://www.youtube.com/");

        uniWebView.Show(true);
    }

    private static string YoutubeHTMLString =
       @"<html>
            <head></head>
            <body style=""margin:0\"">
                <iframe width = ""100%"" height=""100%"" 
                    src=""https://www.youtube.com/embed/Ccj_H__4KGQ"" frameborder=""0"" 
                    allow=""autoplay; encrypted-media"" allowfullscreen>
                </iframe>
            </body>
         </html>";
}
4

1 回答 1

1

我发现您必须在 UniWebView 组件上的 LoadHTMLString() 之前调用 Show()。我在下面显示了 Start() 方法的更正后的最后几行。

    ...
    uniWebView.SetShowSpinnerWhileLoading(true);
    uniWebView.ReferenceRectTransform = gameObject.GetComponent<RectTransform>();

    uniWebView.Show(true);

    uniWebView.LoadHTMLString(YoutubeHTMLString, "https://www.youtube.com/");
}

我不知道为什么这个解决方案有效,但我认为它是一个错误(在 UniWebView、Unity 或 Android 中)。它可能与后台的异步线程有关,这些线程有时会在 Android 上产生有问题的顺序(我使用的是带有 Android 6.0.1 的旧 Nexus 5)。

尽管如此,我希望这对某人有所帮助,因为我有两天的尝试和错误的糟糕日子...... ;-)

于 2018-10-17T16:41:04.427 回答