PlatformServices.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Scripting;
  4. namespace DiamondArrow.Platform
  5. {
  6. public sealed class PlatformServices : MonoBehaviour
  7. {
  8. public string PlayerName { get; private set; }
  9. public Sprite Portrait { get; private set; }
  10. public event Action ProfileChanged;
  11. string pendingId;
  12. Action<bool> pendingReward;
  13. public void Initialize()
  14. {
  15. #if UNITY_IOS && !UNITY_EDITOR
  16. DiamondIosNative.DiamondInitialize(gameObject.name, testAds: 1);
  17. #endif
  18. }
  19. public void ShowReward(Action<bool> completed)
  20. {
  21. if (pendingId != null) { completed(false); return; }
  22. pendingId = Guid.NewGuid().ToString("N");
  23. pendingReward = completed;
  24. #if UNITY_IOS && !UNITY_EDITOR
  25. DiamondIosNative.DiamondShowReward(gameObject.name, pendingId);
  26. #elif UNITY_EDITOR
  27. if (EditorShowReward != null) EditorShowReward(pendingId);
  28. else ReceiveAdResult(pendingId + ":0");
  29. #else
  30. ReceiveAdResult(pendingId + ":0");
  31. #endif
  32. }
  33. #if UNITY_EDITOR
  34. // The Play Mode harness drives the same request IDs and callback path as iOS.
  35. public Action<string> EditorShowReward;
  36. #endif
  37. [Preserve] public void ReceiveAdResult(string message)
  38. {
  39. int separator = message.IndexOf(':');
  40. if (separator < 0 || pendingId != message.Substring(0, separator)) return;
  41. var completed = pendingReward;
  42. pendingReward = null;
  43. pendingId = null;
  44. completed?.Invoke(message.Substring(separator + 1) == "1");
  45. }
  46. [Preserve] public void ReceiveName(string nickname)
  47. {
  48. PlayerName = string.IsNullOrWhiteSpace(nickname) ? null : nickname;
  49. ReleasePortrait();
  50. ProfileChanged?.Invoke();
  51. }
  52. [Preserve] public void ReceivePhoto(string encoded)
  53. {
  54. var texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
  55. try
  56. {
  57. if (!texture.LoadImage(Convert.FromBase64String(encoded), true)) return;
  58. ReleasePortrait();
  59. Portrait = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(.5f, .5f));
  60. texture = null;
  61. ProfileChanged?.Invoke();
  62. }
  63. finally { if (texture) Destroy(texture); }
  64. }
  65. void ReleasePortrait()
  66. {
  67. if (!Portrait) return;
  68. Destroy(Portrait.texture);
  69. Destroy(Portrait);
  70. Portrait = null;
  71. }
  72. void OnDestroy()
  73. {
  74. #if UNITY_IOS && !UNITY_EDITOR
  75. DiamondIosNative.DiamondDetach(gameObject.name);
  76. #endif
  77. ReleasePortrait();
  78. }
  79. }
  80. }