Guest User

Untitled

a guest
Mar 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. using UnityEngine.UI;
  7.  
  8. namespace AppKit
  9. {
  10. [RequireComponent(typeof(Slider))]
  11. public class BindSlider : UIBehaviour
  12. {
  13. [SerializeField]
  14. GameObject target;
  15.  
  16. [SerializeField]
  17. string compName;
  18.  
  19. [SerializeField]
  20. string propName;
  21.  
  22. [SerializeField]
  23. Text label;
  24.  
  25. Slider ui;
  26. Component comp;
  27. FieldInfo field;
  28.  
  29. protected override void Start()
  30. {
  31. ui = GetComponent<Slider>();
  32. ui.onValueChanged.AddListener(OnValueChanged);
  33.  
  34. comp = target.GetComponent(compName);
  35. if (comp == null)
  36. {
  37. Debug.LogErrorFormat("Component: {0} not found in {1}", compName, target);
  38. return;
  39. }
  40.  
  41. Type type = comp.GetType();
  42. BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
  43. field = type.GetField(propName, flag);
  44. if (field == null)
  45. {
  46. Debug.LogErrorFormat("Member: {0} not found in {1}", propName, compName);
  47. return;
  48. }
  49. float value = (float)field.GetValue(comp);
  50. ui.value = value;
  51. }
  52.  
  53. protected override void OnDestroy()
  54. {
  55. if (ui != null)
  56. {
  57. ui.onValueChanged.RemoveListener(OnValueChanged);
  58. ui = null;
  59. }
  60. if (comp != null)
  61. {
  62. comp = null;
  63. }
  64. if (field != null)
  65. {
  66. field = null;
  67. }
  68. }
  69.  
  70. void OnValueChanged(float value)
  71. {
  72. if (field == null)
  73. {
  74. return;
  75. }
  76.  
  77. field.SetValue(comp, value);
  78. if (label != null)
  79. {
  80. label.text = string.Format("{0}: {1:0.0}", propName, value);
  81. }
  82. }
  83. }
  84. }
Add Comment
Please, Sign In to add comment