PasteManager.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Runtime.InteropServices;
  2. using UnityEngine;
  3. using UnityEngine.EventSystems;
  4. using UnityEngine.UI;
  5. namespace TriLibCore.Samples
  6. {
  7. /// <summary>Represents a Class used to add paste capabilities to WebGL projects.</summary>
  8. public class PasteManager : MonoBehaviour
  9. {
  10. #if UNITY_WEBGL && !UNITY_EDITOR
  11. [DllImport("__Internal")]
  12. private static extern void PasteManagerSetup();
  13. #endif
  14. /// <summary>The Paste Manager Singleton instance.</summary>
  15. public static PasteManager Instance { get; private set; }
  16. /// <summary>Checks if the Singleton instance exists.</summary>
  17. public static void CheckInstance()
  18. {
  19. if (Instance == null)
  20. {
  21. Instance = new GameObject("PasteManager").AddComponent<PasteManager>();
  22. }
  23. }
  24. #if UNITY_WEBGL && !UNITY_EDITOR
  25. private void Start()
  26. {
  27. PasteManagerSetup();
  28. }
  29. #endif
  30. /// <summary>Called when the user pastes the given value in the Web-Browser.</summary>
  31. /// <param name="value">The pasted value.</param>
  32. public void Paste(string value)
  33. {
  34. var currentCurrentSelectedGameObject = EventSystem.current.currentSelectedGameObject;
  35. if (currentCurrentSelectedGameObject != null)
  36. {
  37. var inputField = currentCurrentSelectedGameObject.GetComponentInChildren<InputField>();
  38. if (inputField != null)
  39. {
  40. var newText = $"{inputField.text.Substring(0, inputField.selectionAnchorPosition)}{value}{inputField.text.Substring(inputField.selectionFocusPosition)}";
  41. inputField.text = newText;
  42. }
  43. }
  44. }
  45. }
  46. }