Search code examples
javascriptunity-game-engineunity-webgl

How to call external javascript function from jslib plugin Unity webgl


I'm working on a webgl project now and I'm trying to call javascript function in index.html from plugin.jslib

I did google some methods and seems they're not working.
Is there a proper and simple way to do this?

below codes are the ones that i tried.

index.html

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>%UNITY_WEB_NAME%</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
    <script src="TemplateData/UnityProgress.javascript"></script>
    <script src="%UNITY_WEBGL_LOADER_URL%"></script>
    <script type="text/javascript">
        window.CheckLoad = function(){ window.alert('It is working!!'); };
    </script>
    <script>
        var gameInstance = UnityLoader.instantiate("gameContainer", "%UNITY_WEBGL_BUILD_URL%", {onProgress: UnityProgress});
    </script>
</head>
<body>
 ...
</body>
</html>

plugin.jslib

mergeInto(LibraryManager.library {
    Loaded: function()
    {
        window.CheckLoad();
    },
}); 

Unity C# script

public class blablabla : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern void Loaded();

    public static void IsLoaded()
    {
#if !UNITY_EDITOR && UNITY_WEBGL
        Loaded();
#endif
    }

    void Start()
    {
        IsLoaded();
    }
}

Solution

  • Well.. I was stupid.
    turned out it was my mistake and the way to do these stuffs are quite easy.

    For those who might have same question, check below codes.

    index.html

    <!DOCTYPE html>
    <html lang="en-us">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>%UNITY_WEB_NAME%</title>
        <link rel="shortcut icon" href="TemplateData/favicon.ico">
        <link rel="stylesheet" href="TemplateData/style.css">
        <script src="TemplateData/UnityProgress.javascript"></script>
        <script src="%UNITY_WEBGL_LOADER_URL%"></script>
        <script>
            var gameInstance = UnityLoader.instantiate("gameContainer", "%UNITY_WEBGL_BUILD_URL%", {onProgress: UnityProgress});
    
            function CheckLoad(){
               window.alert("WORKING~!");
            }
        </script>
    </head>
    <body>
     ...
    </body>
    </html>
    

    plugin.jslib

    var plugin = {
        Loaded: function()
        {
            CheckLoad();
        }
    };
    
    mergeInto(LibraryManager.library, plugin);