In this section, we will see how to create and use UniWebView with code to enable Carry1st Platform payments. You will learn

  • How to attach UniWebView component to a game object.
  • How to load the Platform Payments webpage and handle loading events.
  • Work with some essential features like JavaScript and UniWebView messaging system.

Creating a WebView

In your Unity project and import UniWebView. After importing the UniWebView, remember to restart the Unity Editor, as well as change the target platform to either "iOS" or "Android" in Build Settings.

In the scene, you want to use UniWebView, add an empty GameObject by GameObject -> Create Empty in the menu. Rename the newly created object to "Controller" or something appropriate. It will be our controller object for the scene. Then, click Assets → Create → C# Script to create a script with "Controller" as its name.

Finally, choose the Controller object in the Hierarchy tab and add Controller.cs component by using the "Add Component" button in the inspector.

Open Controller.cs with any text editor you like and modify the content of that file to:

using System;
using UnityEngine;

public class Controller : MonoBehaviour
{
    private UniWebView webView;
  
    void Start()
    {
        var webViewGameObject = new GameObject("UniWebView");
        webView = webViewGameObject.AddComponent<UniWebView>();
        // set webview to fill frame
        webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
    }
}

This creates a new GameObject with the name UniWebView in the current scene when the Start() method called for the Controller. We also add a UniWebView component to the game object and store the component in a webview.

Load the URL to the webview in the following function and show it.

void Start()
{
    webView.Load(PLATFORM_URL);     
    webView.Show();
}

Handle the screen orientation in the Start() changes are shown below

webView.OnOrientationChanged += (webview, deviceOrientation) =>
        {
            webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
        };