Проблемы с JSON при развертывании игры Unity WebGL в Heroku - PullRequest
0 голосов
/ 07 ноября 2018

все! Я пытаюсь развернуть сборку игры WebGL, которую я сделал в Unity, в своем приложении Heroku. Мне пришлось изменить способ, которым файл index.html сборки WebGL был настроен так, чтобы Heroku рассчитывал найти статические файлы (.js, .css, изображения и т. Д.), Но что-то все равно не так - я получаю следующую ошибку, когда попробуйте проверить страницу index.html локально в Firefox через Heroku:

SyntaxError: JSON.parse: неожиданный символ в строке 1 столбца 1 из данные JSON

Это похоже на проблему, опубликованную здесь недавно: https://answers.unity.com/questions/1334307/unexpected-character-at-line-1-column-1-of-the-jso.html

К сожалению, ни одно из предложенных решений по этому вопросу не помогло мне. Я подозреваю, что это как-то связано с тем, куда я помещаю папку Build из сборки Unity WebGL, которая содержит template.json, файл, который должен быть проанализирован сценарием UnityLoader.js для запуска сборки Unity. Кажется, для этого нет очевидного места, поэтому я поместил его в static / js, поскольку именно там находится UnityLoader.js. Но похоже, что Heroku не может найти папку Build, так как я получаю сообщение об ошибке 404 в интерфейсе командной строки Heroku при каждой загрузке страницы index.html:

"GET /% UNITY_WEBGL_BUILD_URL% HTTP / 1.1" 404 97

Если у кого-то есть понимание того, что я могу делать неправильно при изменении сборки Unity WebGL для Heroku или что могло вызвать ошибку чтения JSON, пожалуйста, сообщите! (Я запустил файл template.json через JSONLint, и это действительно JSON)

Код для моего файла index.html:

<!DOCTYPE html>
{% extends 'workshoptemplate.html' %}

{% load staticfiles %}
{% load static %}

{% block head %}
    <link rel="shortcut icon" href="{% static 'assets/favicon.ico' %}">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <script src="{% static 'js/UnityProgress.js' %}"></script>  
    <script src="{% static 'js/UnityLoader.js' %}"></script>
{% endblock %}

{% block content %}
<!-- <html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Game</title>


    <script>
     // var gameInstance = UnityLoader.instantiate("gameContainer", "Build/templates.json", {onProgress: UnityProgress});
    </script>
  </head> 
  <body> !-->
    <div class="webgl-content">
      <div id="gameContainer" style="width: 960px; height: 600px"></div>
      <div class="footer">
        <div class="webgl-logo"></div>
        <div class="fullscreen" onclick="gameInstance.SetFullscreen(1)"></div>
        <div class="title">Spatial Game #1</div>
      </div>
    </div>

{% endblock %}

{% block javascript %}
    <script type="text/javascript">

        var gameInstance = UnityLoader.instantiate("gameContainer", "Build/templates.json", {onProgress: UnityProgress});
    </script>
{% endblock %}

<!--
    </body>
</html> !-->

Код для файл мастерской.html, который расширяет мой файл index.html:

{% load staticfiles %}
<!DOCTYPE HTML>
<html>

<head>
  <!--     boostrap -->
    <!-- <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1"> -->
      <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
      <!-- Bootstrap -->
    <!-- <link href={% static "css/bootstrap.min.css"%} type='text/css' rel="stylesheet"> -->

      <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
      <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
      <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
      <![endif]-->
  <!--     boostrap above -->
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=10; chrome=1;">
    <meta name="fragment" content="!">
    <meta name="viewport" content="width=device-width">
    <base target="_blank">
    <title>Spatial Games Research</title>
    <link href="{% static "css/formview_st_ltr.css"%}" type='text/css' rel='stylesheet'>
    <link href="{% static "css/mobile_formview_st_ltr.css"%}" type='text/css' rel='stylesheet' media='screen and (max-device-width: 721px)'>
    <link href="{% static "css/index.css"%}" type='text/css' rel='stylesheet'>
    <link rel="stylesheet" type="text/css" href="{% static "css/pnotify.custom.min.css"%}">
    <link href='http://fonts.googleapis.com/css?family=Play' rel='stylesheet' type='text/css'>
    <script type="text/javascript" src="{% static "js/jquery.min.js" %}"></script>
    <script type="text/javascript" src="{% static "js/jquery-ui.min.js" %}"></script>
    <script type="text/javascript" src="{% static "js/pnotify.custom.min.js" %}"></script>
    <script type="text/javascript">
    window.history.forward();
    </script>
    {% block head %}
    {% endblock %}
</head>

<body>

  <div itemscope itemtype="http://schema.org/CreativeWork/FormObject" style="padding-top:90px">
          <meta itemprop="name" content="Spatial Reasoning Test">
          <div class="ss-form-container">
            <div class="ss-top-of-page">
              <div class="ss-form-heading">
            <!-- <h1 class="ss-form-title" dir="ltr">Spatial Reasoning Assessment</h1> -->
              </div>
    </div> 


 <!--    <body dir="ltr" class="ss-base-body">
        <div itemscope itemtype="http://schema.org/CreativeWork/FormObject">
            <meta itemprop="name" content="Spatial Reasoning Test"> 
            <div class="ss-form-container">
              <div class="ss-top-of-page">
                <div class="ss-form-heading">
                    <h1 class="ss-form-title" dir="ltr">Spatial Reasoning Assessment</h1> 
                </div>
            </div> -->

</body>


    {% block content %}
    {% endblock %}

 <!--   <div class="ss-form">
        <form action="" method=POST id=ss-form target=_self onsubmit="return validate_form(this)">
            {% csrf_token %} {% autoescape off %} {{content}} {% endautoescape %}
        </form>
    </div>
        </div>
    <div id="docs-aria-speakable" class="docs-a11y-ariascreenreader-speakable docs-offscreen" aria-live="assertive" role="region" aria-atomic></div>
    </div>
    </div>

</body>
!-->
<script type="text/javascript" src="{% static 'js/logic_index.js' %}"></script>
<script type="text/javascript">

    function saveLog( action, obj, callback ) {
        var pathname = window.location.pathname;
        var log = {"path": pathname, "action": action, "msg": JSON.stringify(obj)};
        console.log("LOG: ");
        console.log(log);
        $.ajax({
            type: "POST",
            url: "/hello/log/",
            data: log,
            success: function(response) {
                console.log("success!");
                if (callback != undefined) callback();
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            },
        });
    }
</script>
<!-- for javascript cookie function -->
<script src="{% static 'js/js.cookie.js' %}"></script>
<script>
    var csrftoken = Cookies.get('csrftoken');



    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

//  comment this out when study is offline PLACE HOLDER
    $(function(){
        saveLog("LOAD", []);
    })


/*  $(function(){
        // initialize tooltips
        $('[data-toggle="tooltip"]').tooltip({
            html: true,
        })
    })*/
</script>
{% block javascript %}
{% endblock %}

</html>
...