Unity WEBGL设置全屏

青春壹個敷衍的年華 提交于 2019-12-18 22:17:26

在webgl平台,直接设置 Screen.fullScreen = true;是不可以成功直接全屏的。我们去官网查看webgl的FullScreen讲解。

Due to security concerns, browsers will only allow locking the cursor or going into full-screen mode in direct response to a user-initiated event (like a mouse click or key press). Unfortunately, Unity does not have separate event and rendering
 loops, so it defers event handling to a point where the browser no longer acknowledges a full-screen or cursor lock request issued from Unity scripting as a direct response to the event which triggered it. As a result, Unity triggers the request on the next user-initiated event, rather than the event that triggered the cursor lock or full-scree request.

说是由于安全考虑,浏览器只允许锁定鼠标和设置全屏模式作为对用户发起事件的直接响应。unity没有单独的事件和呈现循环。所以unity推迟事件响应直到浏览器不承认全屏或者锁定鼠标的请求。所以是在用户下一个发起事件响应请求而不是事件触发全屏请求。

To make this work with acceptable results, you should trigger cursor locking or full-screen requests on mouse/key down events, instead of mouse/key up events. This ensures that when the request is deferred to the next user-initiated event, it is triggered when the user releases the mouse or key.

官方推荐在设置全屏事件放在鼠标或者键盘的down事件上。所以在设置全屏的代码如下:

/// <summary>
    /// 设置全屏
    /// </summary>
    public void SetFullScreen()
    {
        if(!Screen.fullScreen)
        {
            StartCoroutine("FullScreenHandle");
            Screen.fullScreen = true;
        }
    }
 /// <summary>
    /// 检测是否全屏 全屏完成后+TODO
    /// </summary>
    /// <returns></returns>
    IEnumerator FullScreenHandle()
    {
        while (!Screen.fullScreen)
        {
            yield return new WaitForEndOfFrame();
        }
        Debug.Log("quanping"); Top1.gameObject.SetActive(true); Top2.gameObject.SetActive(false);
    }

注意:在设置完全屏后,unity并不会立刻设置全屏,而是等待下一次发起事件触发才会响应。即抬起鼠标后才会去触发设置全屏。将此事件绑定到button的OnPointerDown上。

而退出全屏则没有以上问题。只需要在Onclick上添加退出全屏事件即可,退出请求会立刻发出。

 /// <summary>
    /// 退出全屏
    /// </summary>
    public void QuitFullScreen()
    {
        if (Screen.fullScreen)
        {
            Debug.Log("notquanping"); Top2.gameObject.SetActive(true); Top1.gameObject.SetActive(false);
            Screen.fullScreen = false;
        }
    }

以上是WEBGL设置全屏的坑。希望对你有帮助!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!