using System; using UnityEngine; using UnityEngine.Scripting; namespace DiamondArrow.Platform { public sealed class PlatformServices : MonoBehaviour { public string PlayerName { get; private set; } public Sprite Portrait { get; private set; } public event Action ProfileChanged; string pendingId; Action pendingReward; public void Initialize() { #if UNITY_IOS && !UNITY_EDITOR DiamondIosNative.DiamondInitialize(gameObject.name, testAds: 1); #endif } public void ShowReward(Action completed) { if (pendingId != null) { completed(false); return; } pendingId = Guid.NewGuid().ToString("N"); pendingReward = completed; #if UNITY_IOS && !UNITY_EDITOR DiamondIosNative.DiamondShowReward(gameObject.name, pendingId); #elif UNITY_EDITOR if (EditorShowReward != null) EditorShowReward(pendingId); else ReceiveAdResult(pendingId + ":0"); #else ReceiveAdResult(pendingId + ":0"); #endif } #if UNITY_EDITOR // The Play Mode harness drives the same request IDs and callback path as iOS. public Action EditorShowReward; #endif [Preserve] public void ReceiveAdResult(string message) { int separator = message.IndexOf(':'); if (separator < 0 || pendingId != message.Substring(0, separator)) return; var completed = pendingReward; pendingReward = null; pendingId = null; completed?.Invoke(message.Substring(separator + 1) == "1"); } [Preserve] public void ReceiveName(string nickname) { PlayerName = string.IsNullOrWhiteSpace(nickname) ? null : nickname; ReleasePortrait(); ProfileChanged?.Invoke(); } [Preserve] public void ReceivePhoto(string encoded) { var texture = new Texture2D(2, 2, TextureFormat.RGBA32, false); try { if (!texture.LoadImage(Convert.FromBase64String(encoded), true)) return; ReleasePortrait(); Portrait = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(.5f, .5f)); texture = null; ProfileChanged?.Invoke(); } finally { if (texture) Destroy(texture); } } void ReleasePortrait() { if (!Portrait) return; Destroy(Portrait.texture); Destroy(Portrait); Portrait = null; } void OnDestroy() { #if UNITY_IOS && !UNITY_EDITOR DiamondIosNative.DiamondDetach(gameObject.name); #endif ReleasePortrait(); } } }