Passing array of objects from JavaScript to Unity

Hi,

How can I pass array of objects from browser (JavaScript) to Unity (C#) using SendMessage?

Example -

JavaScript code (embedded in html) -

function book( name, pageCount)
{

this.name = name;
this.pageCount= pageCount;
}

var books = new Array();
books[0] = new book(“Unity Cookbook”, 255);

GetUnity().SendMessage(“Main Camera”, “testFunction”, books);

C# code (in Unity)

class Book {

public string name;
public string pageCount;
}

void testFunction(ArrayList books)
{

Book book = (Book)books[0];
Debug.Log(book.name);
}

Error in log files -

100227 16:22:52 SendMessage: Object is not an array
MissingMethodException: The best match for method testFunction has some invalid parameter.

Thanks,
Ravi

As the docs say: “A single string, integer or float argument must be passed when using SendMessage()”. That’s all you can pass; objects in web Javascript don’t translate to Unity, and vice versa. To send something more complex, you can build multiple parameters joined by a separator into a string (“something,like,this”), and then parse that on the Unity side.

–Eric

Hi Eric,

Thanks for your reply!

Yes, documentation mentions just one argument of type string, int or float.

JSON is one option for sending array of objects. How ever, it’s expensive.

Any suggestions/alternatives?

Thanks,
Ravi

Hi rsm,

An array on browser turn out become an Object[ ] in Unity after the SendMessage(). However, use it be carefully… it may overload your system if used too heavy…
http://forum.unity3d.com/viewtopic.php?t=47058

In fact, I going to study the JSON now :slight_smile:

Good Luck :slight_smile:

In my case, I ended up using JSON, since I am already using it on the Unity side for some interaction with Web API.

Here’s the call from JS in the browser:

unityPlayer.SendMessage(data.Name + “WallScreen”, “SetWallData”, JSON.stringify({ FrameId: $(“#frameId”).val(), Layout: currentLayout() }));

Here’s the code on the unity side (in C#):

void SetWallData(string wallData)
{
// Parameters are passed as JSON and contain the Layout and FrameId fields

JSONNode data = JSON.Parse(wallData);

string layout = data[“Layout”].Value;
int frameId = data[“FrameId”].AsInt;

// do stuff
}

I used the SimpleJSON library to do JSON in Unity.