gree / unity-webview

zlib License
2.25k stars 687 forks source link

How can I interact with C# scripts in my Android app #838

Open binh0804 opened 2 years ago

binh0804 commented 2 years ago

I want to publish an Android application using webview to stream Unity WebGL game. How can I check when user win the game (WebGL) to show a video "Happy birthday" (in Android app). Can I do this stuff???

Thank you. Sorry for my bad English.

KojiNakamaru commented 2 years ago

If you can control the Unity WebGL code, you can put Assets/Plugins/util.jslib with the following content:

mergeInto(LibraryManager.library, {
  SetGameStatus: function(s) {
    window.gameStatus = s;
  }
});

and invoke the above function from C# when "Happy birthday" is played:

public class Main : MonoBehaviour
{
    [DllImport("__internal")]
    private static extern SetGameStatus(string s);

    void Start()
    {
        SetGameStatus("Start");
    }

    void Update()
    {
       ...
       if (ShouldStartMovie())
       {
           SetGameStatus("Happy birthday movie");
           StartMovie();
       }
       ...
    }
}

This WebGL content is shown in a webview displayed by the Android host app. The Android host app can then invoke webViewObject.EvaluateJS("Unity.call(window.gameStatus)") to send the current window.gameStatus value to the Unity side, which is received by the cb: callback.

cf. https://docs.unity3d.com/2020.3/Documentation/Manual/webgl-interactingwithbrowserscripting.html cf. https://github.com/gree/unity-webview/blob/e2ee37af62acc41dd1a87baa4932cd0a1c548197/sample/Assets/Scripts/SampleWebView.cs#L116 cf. https://github.com/gree/unity-webview/blob/e2ee37af62acc41dd1a87baa4932cd0a1c548197/sample/Assets/Scripts/SampleWebView.cs#L38-L43

binh0804 commented 2 years ago

Thanks for you perfect working webview and very good support!

But I cannot know where the msg parameter come from? How to send it from the webview? Thank you.

KojiNakamaru commented 2 years ago

As I wrote above, you can send a string by Unity.call("any message"). It is then passed as the argument msg of the ld: callback.