Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Feedback JavaScript to Unity SendMessage string truncated, null-terminated

Discussion in 'WebGL' started by Fizzr, Nov 7, 2019.

  1. Fizzr

    Fizzr

    Joined:
    Jul 6, 2014
    Posts:
    1
    I found this problem when trying to send binary data from the browser to Unity through the string argument of the unityInstance.SendMessage function. Although the JavaScript portion of my code has no problem with null characters in a string variable, and the receiving C# portion of the code should (according to some light research) be able to handle it as well, somewhere between the two the string gets terminated at the first point of a null character.

    This might be expected behaviour, I don't know, but I couldn't find it documented anywhere and it was a real headscratcher for me. My colleague had similar problems with SendMessage functions where the entire message was not being sent. However, those calls were internal to Unity, and didn't interact with the WebGL part. He found some workaround though, so I cannot confirm that it was the same issue.

    Simplified code example

    Code (JavaScript):
    1. var bin = new Uint8Array();
    2. bin = [97,98,99, 0, 49,50,51,61];
    3. let text = bin2String(bin);
    4. console.log("Conversion is: " + text);
    5. unityInstance.SendMessage("WebInterface", "receiveBinary", text);
    Code (csharp):
    1. public void receiveBinary(string text){
    2.         Debug.Log("Inputted string: " + text);
    3.         Debug.Log("String length: " + text.Length);
    4. }
    Output:
    Conversion is: abc□123=
    Inputted string: abc
    String length: 3


    Note: Added the white box in the output for this post manually, as that is what the browser log shows, but this forum does not display null characters that way
     
  2. diaosuyi

    diaosuyi

    Joined:
    Jan 22, 2016
    Posts:
    2
    Did you ever find a solution to this? I am experiencing the exact same issue Unity 2018
     
  3. JoeMan500

    JoeMan500

    Joined:
    Jul 26, 2022
    Posts:
    4
  4. De-Panther

    De-Panther

    Joined:
    Dec 27, 2009
    Posts:
    555
    When you want to send binary data as string, it's better to use a bin to text encoding, like base64.

    and if you need to send binary data from JS to Unity C# there are other ways instead of SendMessage.
    You can create byte array in Unity, and share it's size and pointer position to JS, and then fill it in JS.