public class World : MonoBehaviour
{
public string PLog(string str)
{
Debug.Log("Log: " + str);
return'success!';
}
}
var str = unityInstance.SendMessage("World", "PLog", "hello");
console.log(str); // success!
public class World : MonoBehaviour
{
public string PLog(string str)
{
Debug.Log("Log: " + str);
return'success!';
}
}
var str = unityInstance.SendMessage("World", "PLog", "hello");
console.log(str); // success!
I think I find the solution:
jslib:
mergeInto(LibraryManager.library, {
On: function(type, cb) {
window.addEventListener(Pointer_stringify(type), cb);
},
Emit: function(type, data) {
window.dispatchEvent(new Event(Pointer_stringify(type)), Pointer_stringify(data));
},
});
unity c#:
public void PLog(string str)
{
Emit("send", str);
}
browser js:
window.addEventListener('send', (str)=>{
console.log('log', str);
});
unityInstance.SendMessage("World", "PLog", "Hello")
Don’t use Pointer_stringify
, it is no longer supported in 2021.2 and onwards.
For examples look at the documentation
Nice! My code:
mergeInto(LibraryManager.library, {
Emit: function(type, data) {
var eventWithData = new CustomEvent(Pointer_stringify(type), { detail: Pointer_stringify(data) });
window.dispatchEvent(eventWithData);
},
});
public void loadset(string parameters)
{
string[ ] parameterArray = parameters.Split(',');
string parentName = parameterArray[0];
string fileName= parameterArray[1];
Emit("send", parentName+","+fileName);
}
var FilesString;
window.addEventListener('send', function(str) {
console.log('log', str);
FilesString=str;
});
function set_js( parentName,fileName) {
var parameters = parentName.toString() + ',' + fileName.toString();
gameInstance.SendMessage("goname", "loadset",parameters);
return FilesString.detail;
};
In your hosted JavaScript code
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player</title>
</head>
<body>
<script>
var myCustomFunction= function(msg) {
console.log("Calling from Unity: " + msg)
}
</script>
</body>
</html>
In unity
Create a file anyname.jslib under Assets/Plugins/
Add your myCustomFunction
mergeInto(LibraryManager.library, {
CallExternalJs: function (message) {
myCustomFunction(UTF8ToString(message));
},
});
Finally in your c# script call this myCustomFunction
Like this:
public class UnityToJavaScript : MonoBehaviour
{
// Declare the external JavaScript function
[DllImport("__Internal")]
private static extern void CallExternalJs(string message);
void Start()
{
// Call the JavaScript function
CallExternalJs("Hello from Unity!");
}
}
That’s it. Enjoy