using System; using System.Runtime.InteropServices; using UnityEngine; // Attach once; the included editor build command creates the scene for you. public class PlayIslandExample : MonoBehaviour { #if UNITY_WEBGL && !UNITY_EDITOR [DllImport("__Internal")] private static extern void PI_Connect(string objectName); [DllImport("__Internal")] private static extern void PI_Report(string objectName, string name, string json); [DllImport("__Internal")] private static extern void PI_Dispose(); #endif [Serializable] private class Progress { public int progress; } [Serializable] private class Result { public int score; public int progress = 100; } private string message = "Connecting…", action; private int stars; private bool busy = true, running, broken; private float startedAt; private void Start() { gameObject.name = "PlayIslandExample"; #if UNITY_WEBGL && !UNITY_EDITOR PI_Connect(gameObject.name); #else broken = true; message = "Editor layout preview. Build Web and launch inside Play Island to connect."; #endif } public void OnConfiguration(string json) { message = "Connected. Start a run."; busy = false; Debug.Log(json); } public void OnError(string reason) { broken = true; busy = false; message = reason + " Reload after fixing the integration."; } public void OnAccepted(string json) { if (action == "started") { stars = 0; running = true; startedAt = Time.realtimeSinceStartup; } if (action == "progress") stars++; if (action == "completed") running = false; busy = false; message = "Accepted: " + action + " · " + stars + " / 5 stars"; Debug.Log(json); } private void Report(string name, string json) { if (busy || broken) return; busy = true; action = name; #if UNITY_WEBGL && !UNITY_EDITOR PI_Report(gameObject.name, name, json); #endif } private void OnGUI() { GUI.matrix = Matrix4x4.Scale(new Vector3(Screen.width / 720f, Screen.height / 540f, 1)); GUILayout.BeginArea(new Rect(30, 30, 660, 480)); GUILayout.Label("Play Island · Collect Five"); GUILayout.Label(message); GUI.enabled = !busy && !broken && !running; if (GUILayout.Button("Start run", GUILayout.Height(65))) Report("started", "{}"); GUI.enabled = !busy && !broken && running && stars < 5; if (GUILayout.Button("Collect a star", GUILayout.Height(65))) Report("progress", JsonUtility.ToJson(new Progress { progress = (stars + 1) * 20 })); GUI.enabled = !busy && !broken && running && stars == 5 && Time.realtimeSinceStartup - startedAt >= 4; if (GUILayout.Button("Finish run", GUILayout.Height(65))) Report("completed", JsonUtility.ToJson(new Result { score = stars * 10 })); GUI.enabled = true; GUILayout.EndArea(); } private void OnDestroy() { #if UNITY_WEBGL && !UNITY_EDITOR PI_Dispose(); #endif } }