Abort at error at jsstacktrace

When i test a preview of the game in the Developer Console, the following error occurs in the browser. This occurs at the moment when it tries to request persistent data from the player. Someone kn...

When i test a preview of the game in the Developer Console, the following error occurs in the browser. This occurs at the moment when it tries to request persistent data from the player. Someone knows what it is? NOTE* During development on Windows and in tests with Open Exported Port everything went well.

Complete log:

https://drive.google.com/open?id=1R4dJx4NSDDMbLirLENz_r0cgoedmS-tk

I would like to get the saved data from the main player with this code.

public void RequestPersistentData()
{
    List<string> connectedUids = new List<string>();
    connectedUids.Clear();
    connectedUids.Add(AirConsole.instance.GetUID(AirConsole.instance.GetMasterControllerDeviceId()));
    AirConsole.instance.RequestPersistentData(connectedUids);
}

First the scene is executed with AirInputManager.cs. Then the main menu scene where the MenuController script is executed is loaded (this is where the error happens). Finally, if the player finishes the game the data is stored on the champion screen where the ChampionManage.cs script runs.

More code: github

asked Dec 11, 2019 at 20:35

Cleiton Machado's user avatar

6

I solved it that way. In WebGL Player settings -> Publishing Settings-> Compression Format, change Gzip to Disabled. For some reason Gzip takes a long time to extract the necessary files when loading the game. And make sure that the name of the root folder where you will build the project has no blank space. «Crazy Game» (Bad). CrazyGame (Good).

To ensure it will work, make sure that the script execution order responsible for managing AirConsole runs at least -90 in Default Time. You can use the Script Execution Order settings (menu: Edit > Project Settings, then select the Script Execution Order__ category).

answered Dec 18, 2019 at 3:37

Cleiton Machado's user avatar

Содержание

  1. Tanks demo broken #87
  2. Comments
  3. SendMessage с параметром массива в единстве webgl
  4. Как я могу решить эту ошибку в игре WebGL Unity?
  5. Понятия не имею, почему я получаю эту ошибку. После создания моего проекта в WebGL и его запуска в окне игры itch.io (в Chrome) он отображает это сообщение, игра не запускается:
  6. Ошибка веб-консоли:
  7. Name already in use
  8. docs-apim / en / docs / troubleshooting / error-handling.md

Tanks demo broken #87

I run out of memory (firefox and chrome), but i’m assuming this is a Unity WebGL playback issue?

The text was updated successfully, but these errors were encountered:

Hmm, it should not take that much memory — how much memory does your system have, and how much does it use before running out?

I have the same problem. It used to work some days ago but now it just say:

«The browser could not allocate enough memory for the WebGL content. If you are the developer of this content, try allocating more memory to your WebGL build in the WebGL player settings.»

I have system 16GB RAM and only chrome is opened with that tab.

I have this issue on Arch Linux with 8gb of ram on Firefox and Google Chrome. Chrome got the music to play for about a second, but both instantly gave an out of memory error.

Still not working, here is the console output:

Invoking error handler due to
Uncaught abort(«Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value 50331648, (2) compile with -s ALLOW_MEMORY_GROWTH=1 which adjusts the size at runtime but prevents some optimizations, (3) set Module.TOTAL_MEMORY to a higher value before the program runs, or if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 «) at Error
at jsStackTrace (tanks.wasm.framework.unityweb:1567:13)
at stackTrace (tanks.wasm.framework.unityweb:1584:12)
at abort (tanks.wasm.framework.unityweb:16551:44)
at abortOnCannotGrowMemory (tanks.wasm.framework.unityweb:1630:3)
at enlargeMemory (tanks.wasm.framework.unityweb:1635:3)
at wasm-function[33580]:70
at wasm-function[33468]:3968
at wasm-function[2583]:3
at wasm-function[6537]:3
at wasm-function[6528]:13
at wasm-function[2694]:694
at wasm-function[2699]:35
at wasm-function[2687]:95
at wasm-function[4981]:128
at wasm-function[4400]:7
at wasm-function[4688]:299
at wasm-function[4683]:550
at wasm-function[4476]:195
at wasm-function[3465]:376
at wasm-function[3436]:1422
at wasm-function[3429]:63
at wasm-function[33750]:12
at dynCall_v [Object.UnityLoader.7a204835ae937c2b3ab5cd9517cfc805.Module.dynCall_v] (tanks.wasm.framework.unityweb:16273:86)
at browserIterationFunc (tanks.wasm.framework.unityweb:2612:30)
at runIter [Object.runIter] (tanks.wasm.framework.unityweb:2728:13)
at Browser_mainLoop_runner (tanks.wasm.framework.unityweb:2667:26)
If this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.

Wow, I found a workaround. Open the tank demo page at http://webassembly.org/demo/

  1. Click «Play WebAssembly» button
  2. When you see the «Made with Unity» then immediately click to an other tab page
  3. Wait some second
  4. Switch back to the tank demo page and voila

Источник

SendMessage с параметром массива в единстве webgl

Unity SendMessage может передавать только один параметр, и это может быть массив. Итак, я вызываю свой sendMessage для javascript и вызываю метод С# (фактически метод webgl)

но получаю эту ошибку

Invoking error handler due to

Uncaught 2,2,2 is does not have a type which is supported by SendMessage. [Violation] ‘click’ handler took 8994ms blob:http://localhost/1ff50200-cb3a-4367-ab45-f02e9734fac2:2 Uncaught 2,2,2 is does not have a type which is supported by SendMessage.

onclick @ (index):65 (index):65

[Violation] ‘click’ handler took 9000ms

Muhammad Faizan Khan

SendMessage(objectName, methodName, value);

Where objectName is the name of an object in your scene; methodName is the name of a method in the script, currently attached to that object; value can be a string, a number, or can be empty.

-> нет, это не может быть массив

Но кажется, вы хотите передать позицию, чтобы в качестве обходного пути вы могли передать строку типа «2,2,2» и использовать

или что-то вроде того

Я бы отправил его как JSON только ради стандарта.

@Everts звучит для меня немного излишним, поскольку просто передает 3 числа с плавающей запятой без какой-либо дополнительной структуры, но, конечно, почему бы и нет, ^^ потребуется больше пропускной способности;)

@derHugo Спасибо, глупый я, я смешивал вещи и думал, что третье значение также может быть массивом. В любом случае спасибо за поправку. Я уже делаю конкатенацию и разбиваю строку, но ищу другой лучший способ. По этой причине попробуйте решение Shingo. Кажется намного яснее и лучше.

Muhammad Faizan Khan

@MuhammadFaizanKhan, наверное, это правда, но на самом деле он не ответил на вопрос, почему это не работает;)

@derHugo Я хочу принять ответ Шинго, но вы правильно поняли.

Источник

Как я могу решить эту ошибку в игре WebGL Unity?

Понятия не имею, почему я получаю эту ошибку. После создания моего проекта в WebGL и его запуска в окне игры itch.io (в Chrome) он отображает это сообщение, игра не запускается:

An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was: uncaught exception: abort(180) at jsStackTrace (WebGL.wasm.framework.unityweb:8:22313) stackTrace (WebGL.wasm.framework.unityweb:8:22484) [email protected]:///C:/Users/wujtm_000/Desktop/WebGL/Build/UnityLoader.js:4:11118 abort (WebGL.wasm.framework.unityweb:8:483539) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[45753]:0xda48f7 (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[22089]:0x9023d7) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[24498]:0x95f899 (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[22992]:0x93c06c) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[45533]:0xda3cc0 UnityModule [UnityModule/Module.dynCall_iiiii] (WebGL.wasm.framework.unityweb:8:458801) invoke_iiiii (WebGL.wasm.framework.unityweb:8:335855) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[43654]:0xd4f185 (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[43125]:0xd37edc) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[4225]:0x18b90c (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[4224]:0x18b835) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10198]:0x3c205a (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10182]:0x3c0d4e) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[12109]:0x4b637b (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[12108]:0x4b6095) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10577]:0x3ed282 (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10288]:0x3caa9b) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10288]:0x3caab0 (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10283]:0x3ca5ba) @blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[10276]:0x3c881e (blob:null/721358bf-caaa-4408-babf-350932a4b11a line 8 > WebAssembly.instantiate:wasm-function[45547]:0xda3ef2) UnityModule [UnityModule/Module.dynCall_v] (WebGL.wasm.framework.unityweb:8:467249) browserIterationFunc (WebGL.wasm.framework.unityweb:8:175900) runIter (WebGL.wasm.framework.unityweb:8:178973) Browser_mainLoop_runner (WebGL.wasm.framework.unityweb:8:177435)

Ошибка веб-консоли:

Invoking error handler due to Uncaught abort(180) at Error at jsStackTrace (WebGL.wasm.framework.unityweb:8:22313) at stackTrace [Object.stackTrace] (WebGL.wasm.framework.unityweb:8:22484) at Object.onAbort (https://v6p9d9t4.ssl.hwcdn.net/html/2312897/WebGL/Build/UnityLoader.js:4:11118) at abort (WebGL.wasm.framework.unityweb:8:483549) at :wasm-function[45753]:0xda48f7 at :wasm-function[22089]:0x9023d7 at :wasm-function[24498]:0x95f899 at :wasm-function[22992]:0x93c06c at dynCall_iiiii (:wasm-function[45533]:0xda3cc0) at dynCall_iiiii [Object.dynCall_iiiii] (WebGL.wasm.framework.unityweb:8:458801) at invoke_iiiii (WebGL.wasm.framework.unityweb:8:335871) at :wasm-function[43654]:0xd4f185 at :wasm-function[43125]:0xd37edc at :wasm-function[4225]:0x18b90c at :wasm-function[4224]:0x18b835 at :wasm-function[10198]:0x3c205a at :wasm-function[10182]:0x3c0d4e at :wasm-function[12109]:0x4b637b at :wasm-function[12108]:0x4b6095 at :wasm-function[10577]:0x3ed282 at :wasm-function[10288]:0x3caa9b at :wasm-function[10288]:0x3caab0 at :wasm-function[10283]:0x3ca5ba at :wasm-function[10276]:0x3c881e at dynCall_v (:wasm-function[45547]:0xda3ef2) at dynCall_v [Object.dynCall_v] (WebGL.wasm.framework.unityweb:8:467249) at browserIterationFunc (WebGL.wasm.framework.unityweb:8:175912) at runIter [Object.runIter] (WebGL.wasm.framework.unityweb:8:178973) at Browser_mainLoop_runner (WebGL.wasm.framework.unityweb:8:177435) DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8 Uncaught abort(180) at Error at jsStackTrace (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:22313) at Object.stackTrace (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:22484) at Object.onAbort (https://v6p9d9t4.ssl.hwcdn.net/html/2312897/WebGL/Build/UnityLoader.js:4:11118) at abort (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:483549) at :wasm-function[45753]:0xda48f7 at :wasm-function[22089]:0x9023d7 at :wasm-function[24498]:0x95f899 at :wasm-function[22992]:0x93c06c at dynCall_iiiii (:wasm-function[45533]:0xda3cc0) at Object.dynCall_iiiii (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:458801) at invoke_iiiii (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:335871) at :wasm-function[43654]:0xd4f185 at :wasm-function[43125]:0xd37edc at :wasm-function[4225]:0x18b90c at :wasm-function[4224]:0x18b835 at :wasm-function[10198]:0x3c205a at :wasm-function[10182]:0x3c0d4e at :wasm-function[12109]:0x4b637b at :wasm-function[12108]:0x4b6095 at :wasm-function[10577]:0x3ed282 at :wasm-function[10288]:0x3caa9b at :wasm-function[10288]:0x3caab0 at :wasm-function[10283]:0x3ca5ba at :wasm-function[10276]:0x3c881e at dynCall_v (:wasm-function[45547]:0xda3ef2) at Object.dynCall_v (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:467249) at browserIterationFunc (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:175912) at Object.runIter (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:178973) at Browser_mainLoop_runner (blob:https://v6p9d9t4.ssl.hwcdn.net/cf55a5c5-c403-41ef-aab8-de035b7ea92b:8:177435) DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME 29cf55a5c5-c403-41ef-aab8-de035b7ea92b:8 An abnormal situation has occurred: the PlayerLoop internal function has been called recursively. Please contact Customer Support with a sample project so that we can reproduce the problem and troubleshoot it. (Filename: Line: 377)

Если вам нужен Unity Launcher js. код — я не могу использовать его здесь, потому что в нем слишком много букв, приват.

Вещи, которые я пробовал:

  • перестройка проекта
  • запускать его локально в Firefox, который обычно работал, но отображается та же ошибка .
  • обновление Unity до последней версии
  • сделал еще один, но очень маленький проект и построил его WebGL — сработало . Я не знаю, как сделать так, чтобы большой проект работал, есть предложения .

Источник

Name already in use

docs-apim / en / docs / troubleshooting / error-handling.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

When errors/exceptions occur in the system, the API Manager throws JSON-based error responses to the client by default.

Fault Sequence Description
fault.xml This is the primary fault sequence that gets invoked when an error occurs during the execution of an API resources
main.xml This sequence is called when the endpoint being called does not exist
_auth_failure_handler_.xml This sequence is called when an API authentication error is encountered
_production_key_error_.xml This sequence is called when a Production key is used to invoke an API that does not have a Production endpoint defined
_sandbox_key_error_.xml This sequence is called when a Sandbox key is used to invoke an API that does not have a Sandbox endpoint defined
_throttle_out_handler_.xml This sequence is called when a given request to an API gets throttled out
_token_fault_.xml This sequence is called when there is an error in invoking the token API
_resource_mismatch_handler_.xml This sequence is called when a matching resource cannot be found by the gateway to the corresponding resource being invoked
_cors_request_handler_.xml This sequence enables sending CORS specific headers when the CORS specific configuration ( CORSConfiguration ) is enabled in WSO2 API Manager in the /repository/conf/deployment.toml file.
_threat_fault_.xml This sequence is called to send error messages with regard to threat detection.
dispatchSeq.xml This sequence is defined as a default handler for any inbound WebSocket calls.
outDispatchSeq.xml This sequence is defined to handle any outbound WebSocket calls.

Given below are some error codes and their meanings.

API handlers error codes

The maximum number of requests that can be made to the API within a designated time period is reached and the API is throttled for the user.

Sending/Receiving messages beyond authorized application level

Unclassified authentication failure

Invalid authentication information provided.

The error code 900904 (Access token inactive) is deprecated from API Manager 1.9.0 onwards. Alternatively, error code 900901 will be sent when the token is inactive.

Incorrect access token type is provided

The access token type used is not supported when invoking the API. The supported access token types are application and user accesses tokens. See Access Tokens.

No matching resource found in the API for the given request

The requested API is temporarily blocked

The subscription to the API is inactive

The access token does not allow you to access the requested resource

Can not access the required resource with the provided access token. Check the valid resources that can be accessed with this token.

Error code Error Message Description Example
700700 API blocked This API has been blocked temporarily. Please try again later or contact the system administrators. Invoke an API which is in the BLOCKED lifecycle state
900422 Invalid GraphQL query Syntax of the provided GraphQL query is invalid Invoking a GraphQL API which has a invalid query
900800 Message throttled out Invoke an API exceeding the tier limit
900801 Hard limit exceeded Hard throttle limit has been reached Invoke an API exceeding the hard throttle limit
900802 Resource level throttle out Message is throttled out because resource level has exceeded Sending/Receiving messages beyond authorized resource level
900803 Application level throttle out Message is throttled out because application level is exceeded
900804 Subscription level throttled out Message throttled out due to subscription level throttling limit reached. Sending/Receiving messages beyond configured throttling limit of subscription level policy.
900805 Message blocked Accessing an API which is blocked on user, IP, application, or API Context. An admin user can block API invocations in real time by user, IP, application, or API context. The API invocation meets the blocked condition.
900806 Custom policy throttled out Message throttled out due to exceeding the limit configured through the custom throttling policy rules. The API invocations meet custom throttle policy rules, exceeding the limits of the configured custom policy.
900807 Message throttled out Messaged throttled out because of exceeding the burst control/rate limit (requests per second) in the subscription level policy. Sending/Receiving messages exceeding the configured burst control/rate limit within second.
900900 An unspecified error has occurred Backend service for key validation is not accessible when trying to invoke an API
900901 When the access token is invalid, inactive or expired.
900902 No authentication information provided Accessing an API without Authorization: Bearer header
900905 Invoke an API with application token, where the resource only allows application user tokens
900906 A resource with the name in the request can not be found in the API. Invoke an API resource that is not available
900907 Happens when the API user is blocked. Invoke API resource with a subscription that has been blocked by the API publisher
900908 The user invoking the API has not been granted access to the required resource. Invoke an unsubscribed API
900909 The status of the API has changed to an inaccessible/unavailable state. Invoke an API resource with a subscription that has not yet been approved by the administrator.
900910 Invoke API resource with an access token that is not generated to be used with the resource’s scope.
102511 Incomplete payload The payload sent with the request is too large and the client is unable to keep the connection alive until the payload is completely transferred to the API Gateway Sending a large PDF file with the POST request

Sequences error codes

Error code Description
900901 Production/sandbox key offered to the API with no production/sandbox endpoint
400 Server cannot process the request due to an error in the request sent by the client
403 No matching resource found in the API for the given request

In addition to the above error codes, we have engaged Synapse-level error codes to the default fault sequence and custom fault sequences (e.g., _token_fault_.xml ) of the API Manager. For information, see Error Handling in WSO2 Enterprise Integrator (WSO2 EI) documentation.

Transport error codes

Error Code Detail
101000 Receiver input/output error sending
101001 Receiver input/output error receiving
101500 Sender input/output error sending
101501 Sender input/output error receiving
101503 Connection failed
101504 Connection timed out (no input was detected on this connection over the maximum period of inactivity)
101505 Connection closed
101506 NHTTP protocol violation
101507 Connection canceled
101508 Request to establish new connection timed out
101509 Send abort
101510 Response processing failed

If the HTTP PassThrough transport is used, and a connection-level error occurs, the error code is calculated using the following equation:

Error code = Base error code + Protocol State

There is a state machine in the transport sender side, where the protocol state changes according to the phase of the message.

Following are the possible protocol states and the description for each:

REQUEST_READY (0) Connection is at the initial stage ready to send a request REQUEST_HEAD(1) Sending the request headers through the connection REQUEST_BODY(2) Sending the request body REQUEST_DONE(3) Request is completely sent RESPONSE_HEAD(4) The connection is reading the response headers RESPONSE_BODY(5) The connection is reading the response body RESPONSE_DONE(6) The response is completed CLOSING(7) The connection is closing CLOSED(8) The connection is closed

Since there are several possible protocol states in which a request can time out, you can calculate the error code accordingly using the values in the table above. For example, in a scenario where you send a request and the request is completely sent to the backend, but a timeout happens before the response headers are received, the error code is calculated as follows:

In this scenario, the base error code is CONNECTION_TIMEOUT(101504) and the protocol state is REQUEST_DONE(3).

Error code = 101504 + 3 = 101507

These Transport error codes are used in Advanced Configurations of Endpoints .

Custom error messages

To send a custom message with a custom HTTP status code, you execute an additional sequence that can generate a new error message. You then override the message body, HTTP status code and other values.

The following steps demonstrate how to override a throttled-out message’s HTTP status code as a custom error message:

Источник

Нужно создать скрипт, например, с именем app.js. После сборки в WebGL подключить этот скрипт в index.html. А ещё скачать скрипт «socket.io client» (я прикрепил его к сообщению)

Итого, в index.html нужно только это вставить внутрь тега <body></body>:

Javascript
1
2
      <script src="socket.io-1.4.8.js"></script>
      <script src="app.js"></script>

В app.js для подключения к серверу достаточно написать:

Javascript
1
var socket = io();

Но, чтобы не было проблемы кто раньше инициализируется app.js или start-методы в Unity, я помещаю инициализацию socket.io в функцию init:

app.js

Javascript
1
2
3
4
5
var init = function ()
{
    console.log("init");
    var socket = io();
}

В C# вызываю init() так:

Network.cs

C#
1
2
3
4
5
6
public class Network : MonoBehaviour
{
    void Start()
    {
        Application.ExternalCall("init");
    }

После срабатывания init() на сервере сработает обработчик «connection» (у меня index.html и все .js скрипты находятся в папке public):

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var shortid = require("shortid");
 
app.use(express.static(__dirname + "/public"));
 
io.on("connection", function (socket)
{
    var thisPlayerId = shortid.generate();
 
    console.log("client connected, id: ", thisPlayerId);
 
    socket.emit("hello", {id: thisPlayerId});
});

Сервер, после срабатывания, обработчика «connection» пошлёт сообщение «hello», в котором будет находиться id этого клиента.

В клиенте (в app.js) напишите обработчик сообщения «hello». В этом обработчике выведем сообщение в консоль и передадим в C# скрипт:

app.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var init = function ()
{
    console.log("init");
    var socket = io();
 
    socket.on("hello", function (data)
    {
        console.log(data); // Выводим id, который приняли от сервера
        uSendMessage("Network", "OnHello", JSON.stringify(data)); // Передаём принятое сообщение
                        // объекту класса "Network", методу "OnHello"
    });
 
    var uSendMessage = function (obj, func, what)
    {
        SendMessage(obj, func, what); // WebGL
        //u.getUnity().SendMessage(obj, func, what); // WebPlayer
    };
 
}

На клиете в C# можно вывести принятое от сервера id так:

Network.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using System;
 
[Serializable]
public class PlayerInfo
{
    public string id;
}
 
public class Network : MonoBehaviour
{
    void Start()
    {
        Application.ExternalCall("init");
        //players = new Dictionary<string, GameObject>();
    }
 
    public void OnRegister(string data)
    {
        string id = Helpers.GetPlayerInfo(data).id;
        Debug.Log(id);
    }
}

Helpers.cs

C#
1
2
3
4
5
6
7
8
9
10
using UnityEngine;
using System.Collections;
 
public class Helpers
{
    public static PlayerInfo GetPlayerInfo(string data)
    {
        return JsonUtility.FromJson<PlayerInfo>(data);
    }
}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Abnormal termination error code 1
  • Abnormal program termination как исправить bloody 6
  • Abnormal build process termination intellij ошибка
  • Abm01 hdims13 fe01 ошибка f34
  • Ableton live как изменить тему

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии