将回调从Unity传递回JavaScript并返回Unity

时间:2017-06-29 19:33:22

标签: javascript c# unity3d unity-webgl

我正在尝试运行一个Action,它将数据发送到浏览器上的javascript,当浏览器完成后运行回调,当回调完成时,它运行C#中运行的项目原始回调。

以下是致电订单:GameSmart.User.IsGuest(Action origCallback) -> IsGuestUser(/*Executes the javascript*/) -> GuestResponse(string json) -> origCallback()

编译并运行游戏后,我在chrome控制台中收到以下消息:

  

MarshalDirectiveException:无法编组类型'GameSmart.Response`1< GameSmart.IsGuestResponse>'。

我不确定这是说什么,甚至意味着什么。有什么我做错了吗?

这是 GameSmart.User 类:

public class User : API {
  [DllImport("__Internal")]
  public static extern void IsGuestUser(Response<IsGuestResponse> response);

  [MonoPInvokeCallback(typeof(Action))]
  public static void GuestResponse(Response<IsGuestResponse> r, string data) {
    r.callback(JsonUtility.FromJson<IsGuestResponse>(data));
  }

  public static void IsGuest(Action<IsGuestResponse> callback) {
    IsGuestUser(new Response<IsGuestResponse>(callback));
  }
}

以下是响应/响应类:

public class Respond { }

public class Response<T> : Respond {
  public Action<T> callback;

  public Response(Action<T> cb) {
    callback = cb;
  }

  public void Action(Action act, params object[] args) {
    act();
  }

}

JavaScript部分如下所示:

var GameSmartJs = {
  $GameSmartJs: {},

  IsGuestUser: function (obj) {
    gamesmart.user.isGuest(function (result) {
      this.runCallback('GuestResponse', obj, result);
    });
  },

  runCallback: function (callbackName, callback, result) {
    GameSmartJs[callbackName] = callback;
    Runtime.dynCall('vZ', callback, Pointer_stringify(result));
  }

};

autoAddDeps(GameSmartJs, '$GameSmartJs');
mergeInto(LibraryManager.library, GameSmartJs);

修改

根据@Programmer的建议,要使用_mallocwriteStringToMemory,我尝试了这一点,它会产生相同的错误消息。

IsGuestUser: function (obj) {
  gamesmart.user.isGuest(function (result) {
    GameSmartUser.GuestResponse = obj;
    var buffer = _malloc(lengthBytesUTF8(result) + 1);
    writeStringToMemory(result, buffer);
    Runtime.dynCall('vZ', obj, buffer);
  });
},

1 个答案:

答案 0 :(得分:0)

对于遇到的下一个灵魂:

Runtime.dynCall('vZ', obj, buffer);

应更改为

Runtime.dynCall('vi', obj, [buffer]);