ComponentExtensions.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. namespace XUnity.AutoTranslator.Plugin.Core.Extensions
  8. {
  9. public static class ComponentExtensions
  10. {
  11. private static readonly string TextPropertyName = "text";
  12. public static string GetText( this object ui )
  13. {
  14. string text = null;
  15. var type = ui.GetType();
  16. if( ui is Text )
  17. {
  18. text = ( (Text)ui ).text;
  19. }
  20. else if( ui is GUIContent )
  21. {
  22. text = ( (GUIContent)ui ).text;
  23. }
  24. else
  25. {
  26. // fallback to reflective approach
  27. text = (string)ui.GetType()?.GetProperty( TextPropertyName )?.GetValue( ui, null );
  28. }
  29. return text ?? string.Empty;
  30. }
  31. public static void SetText( this object ui, string text )
  32. {
  33. var type = ui.GetType();
  34. if( type == Constants.Types.UguiNovelText )
  35. {
  36. Logger.Current.Info( "Setting NovelText: " + text );
  37. ( (Text)ui ).text = string.Empty;
  38. ( (Text)ui ).text = text;
  39. type.GetProperty( "LengthOfView" )?.GetSetMethod()?.Invoke( ui, new object[] { text.Length } );
  40. }
  41. else if( ui is Text )
  42. {
  43. ( (Text)ui ).text = text;
  44. }
  45. else if( ui is GUIContent )
  46. {
  47. ( (GUIContent)ui ).text = text;
  48. }
  49. else
  50. {
  51. // fallback to reflective approach
  52. type.GetProperty( TextPropertyName )?.GetSetMethod()?.Invoke( ui, new[] { text } );
  53. }
  54. }
  55. }
  56. }