VR Development Framework
v 1.0.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events Pages
AVRUI_Link_Toggle.cs
1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4 using UnityEditor;
5 using UnityEngine.UI;
6 
7 using AVR.Core;
8 
9 namespace AVR.UI.Link {
10  [ExecuteInEditMode]
11  [RequireComponent(typeof(Toggle))]
13  {
14  public override List<System.Type> validTypes => new List<System.Type> {typeof(bool)};
15 
16  private Toggle input;
17 
18  protected virtual UnityEngine.Events.UnityAction<bool> 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<Toggle>();
35 
36  if (input) old_value = input.isOn.ToString();
37  }
38 
39  public override void updateValue()
40  {
41  bool val = input.isOn;
42 
43  // Update it to the target, if possible.
44  try {
45  switch (memberType)
46  {
47  case MemberType.FIELD:
48  {
49  target.GetType().GetField(field).SetValue(target,
50  System.Convert.ChangeType(val, target.GetType().GetField(field).FieldType)
51  );
52  break;
53  }
54  case MemberType.PROPERTY:
55  {
56  target.GetType().GetProperty(field).SetValue(target,
57  System.Convert.ChangeType(val, target.GetType().GetProperty(field).PropertyType)
58  );
59  break;
60  }
61  }
62  }
63  catch(System.Exception) {
64  AVR_DevConsole.cwarn("Could not update the given target value to "+val, this);
65  }
66  }
67 
68  private string old_value;
69 
70  public override void updateOutput()
71  {
72  bool current_value = false;
73 
74  switch (memberType)
75  {
76  case MemberType.FIELD:
77  {
78  current_value = (bool)target.GetType().GetField(field).GetValue(target);
79  break;
80  }
81  case MemberType.PROPERTY:
82  {
83  current_value = (bool)target.GetType().GetProperty(field).GetValue(target);
84  break;
85  }
86  }
87 
88  input.isOn = current_value;
89 
90 #if UNITY_EDITOR
91  if (old_value != current_value.ToString() && !Application.isPlaying)
92  {
93  EditorUtility.SetDirty(input);
94  old_value = current_value.ToString();
95  }
96 #endif
97  }
98  }
99 }