VR Development Framework
v 1.0.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events Pages
AVRUI_Link_Slider.cs
1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4 using UnityEngine.UI;
5 using UnityEditor;
6 
7 using AVR.Core;
8 
9 namespace AVR.UI.Link {
10  [ExecuteInEditMode]
11  [RequireComponent(typeof(Slider))]
13  {
14  public override List<System.Type> validTypes => new List<System.Type> {typeof(float), typeof(int), typeof(double)};
15 
16  private Slider input;
17 
18  protected virtual UnityEngine.Events.UnityAction<float> updateValueListener => delegate { this.updateValue(); };
19 
20  public override void setup() {
21  init();
22 
23  updateOutput();
24 
25  // Make sure we have the adequate persisten listeners by (possibly) removing and re-adding
26  #if UNITY_EDITOR
27  UnityEditor.Events.UnityEventTools.RemovePersistentListener(input.onValueChanged, updateValueListener);
28  UnityEditor.Events.UnityEventTools.AddPersistentListener(input.onValueChanged, updateValueListener);
29  #endif
30 
31  }
32 
33  public override void init() {
34  if(!input) input = GetComponent<Slider>();
35 
36  if (input) old_value = input.value.ToString();
37  }
38 
39  public override void updateValue()
40  {
41  // Get the value currently displayed
42  float val = input.value;
43 
44  // Update it to the target, if possible.
45  try {
46  switch (memberType)
47  {
48  case MemberType.FIELD:
49  {
50  target.GetType().GetField(field).SetValue(target,
51  System.Convert.ChangeType(val, target.GetType().GetField(field).FieldType)
52  );
53  break;
54  }
55  case MemberType.PROPERTY:
56  {
57  target.GetType().GetProperty(field).SetValue(target,
58  System.Convert.ChangeType(val, target.GetType().GetProperty(field).PropertyType)
59  );
60  break;
61  }
62  }
63  }
64  catch(System.Exception) {
65  AVR_DevConsole.cwarn("Could not update the given target value to "+val, this);
66  }
67  }
68 
69  private string old_value;
70 
71  public override void updateOutput()
72  {
73  float current_value = 0f;
74 
75  switch (memberType)
76  {
77  case MemberType.FIELD:
78  {
79  current_value = (float)target.GetType().GetField(field).GetValue(target);
80  break;
81  }
82  case MemberType.PROPERTY:
83  {
84  current_value = (float)target.GetType().GetProperty(field).GetValue(target);
85  break;
86  }
87  }
88 
89  input.value = current_value;
90 
91 #if UNITY_EDITOR
92  if (old_value != current_value.ToString() && !Application.isPlaying)
93  {
94  EditorUtility.SetDirty(input);
95  old_value = current_value.ToString();
96  }
97 #endif
98  }
99  }
100 }