Search code examples
callbackdelegatesunity-game-engineunityscriptplayer.io

Unity: Javascript callbacks, delegates


I would like to use Player.IO from Yahoo Games Network in my Unity javascript code. PlayerIO provides example project for unity written only in C# so I am having problems with getting the callbacks work.

PlayerIO.Connect description from Player.IO documentation for Unity (available here):

public void Connect (string gameId, string connectionId, string userId, string auth,
string partnerId, String[] playerInsightSegments,
Callback<Client> successCallback, Callback<PlayerIOError> errorCallback)

So how to make these callbacks work?

The following part of the question shows the ways I have already tried, but didn't work.


Firstly I've tried this way (as I know from javascript):

function success(client : Client) {
  //function content
}
PlayerIOClient.PlayerIO.Connect(pioGameId, pioConnectionId, pioUserId, pioAuth, pioPartnerId, success, failed);

.


That was not right and I've learned that I should use delegates. From Unity3D official tutorials (available here), the right use of delegates in JS would be like this (using the Function type):

var successDelegate : Function;

function success(client : Client) {
  //function content
}

function Start () {
    successDelegate = success;
    PlayerIOClient.PlayerIO.Connect(pioGameId, pioConnectionId, pioUserId, pioAuth, pioPartnerId, success, failed);
}

This is causing the following error:

InvalidCastException: Cannot cast from source type to destination type. Main+$Start$2+$.MoveNext ()

.


After that I've found a topic on Player.IO forum (available here) called Utilizing Player.IO in Unity Javascript. Suggested approach of creating delegates in JS by the author of that topic: go straight to the .Net type and declare them as System.Delegate.

var pioConnectSuccessCallback : System.Delegate;

function success(client : Client) {
  //function content
}

function Start () {
  pioConnectSuccessCallback = System.Delegate.CreateDelegate(typeof(PlayerIOClient.Callback.<PlayerIOClient.Client>), this, "success");
  PlayerIOClient.PlayerIO.Connect(pioGameId, pioConnectionId, pioUserId, pioAuth, pioPartnerId, pioConnectSuccessCallback, pioConnectErrorCallback);
}

This is unfortunately also not working for me, although the guys on the forum present it as a working solution (but it may be outdated).

The error I'm getting:

Assets/Main.js(51,35): BCE0023: No appropriate version of 'PlayerIOClient.PlayerIO.Connect' for the argument list '(String, String, String, String, String, System.Delegate, System.Delegate)' was found.

So it seems like Connect method doesn't like System.Delegate as a parameter or those were not initialized well.


Solution

  • The 3rd way is working, the function is expecting 8 parameters and that was why it didn't work for me.