Demo.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using com.bbbirder.injection;
  2. using UnityEngine;
  3. using System;
  4. using UnityEngine.Assertions;
  5. using System.Reflection;
  6. using System.Collections.Generic;
  7. public class Demo : MonoBehaviour
  8. {
  9. void Start()
  10. {
  11. // FixHelper.InstallAll();
  12. print("press SPACE to replace methods");
  13. }
  14. void Update()
  15. {
  16. Debug.Log(DemoModal.Salute());
  17. Debug.Log(new DemoModal().ThisSalute());
  18. Debug.Log(new DemoModal().Add(4, 1.2f));
  19. if (Input.GetKeyDown(KeyCode.Space))
  20. {
  21. FixHelper.InstallAll();
  22. }
  23. }
  24. #region Fix
  25. static Func<int> RawSalute;
  26. static int Salute()
  27. {
  28. return 2;
  29. }
  30. static Func<DemoModal, int> RawThisSalute;
  31. static int ThisSalute(DemoModal demo)
  32. {
  33. return 2;
  34. }
  35. static Func<DemoModal, int, float, float> RawAdd;
  36. static float Add(DemoModal demo, int i, float f)
  37. {
  38. Debug.Log($"Add {i} + {f} is {i + f}");
  39. return i + f;
  40. }
  41. static Action<object> RawLog;
  42. [HideInCallstack]
  43. static void Log(object msg)
  44. {
  45. RawLog?.Invoke("msg:" + msg);
  46. }
  47. internal class MethodReplacer : IInjection
  48. {
  49. static BindingFlags bindingFlags = 0
  50. | BindingFlags.Public
  51. | BindingFlags.NonPublic
  52. | BindingFlags.Static
  53. ;
  54. public IEnumerable<InjectionInfo> ProvideInjections()
  55. {
  56. yield return InjectionInfo.Create<Func<int>>(
  57. DemoModal.Salute,
  58. Salute,
  59. f => RawSalute = f
  60. );
  61. yield return InjectionInfo.Create(
  62. typeof(DemoModal).GetMethod(nameof(DemoModal.ThisSalute)),
  63. typeof(Demo).GetMethod(nameof(Demo.ThisSalute), bindingFlags),
  64. f => RawThisSalute = (Func<DemoModal, int>)f
  65. );
  66. yield return InjectionInfo.Create(
  67. typeof(DemoModal).GetMethod(nameof(DemoModal.Add)),
  68. typeof(Demo).GetMethod(nameof(Demo.Add), bindingFlags),
  69. f => RawAdd = (Func<DemoModal, int, float, float>)f
  70. );
  71. /* yield return InjectionInfo.Create<Action<object>>(
  72. Debug.Log,
  73. Log,
  74. f => RawLog = f
  75. );*/
  76. }
  77. }
  78. #endregion
  79. }