Created
March 14, 2018 10:34
-
-
Save asus4/5ace55119d4fd9d6d98a2f0893f9c965 to your computer and use it in GitHub Desktop.
[Unity] Bind a slider UI value into any SerializeField, even private field.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
using UnityEngine; | |
using UnityEngine.EventSystems; | |
using UnityEngine.UI; | |
namespace AppKit | |
{ | |
[RequireComponent(typeof(Slider))] | |
public class BindSlider : UIBehaviour | |
{ | |
[SerializeField] | |
GameObject target; | |
[SerializeField] | |
string compName; | |
[SerializeField] | |
string propName; | |
[SerializeField] | |
Text label; | |
Slider ui; | |
Component comp; | |
FieldInfo field; | |
protected override void Start() | |
{ | |
ui = GetComponent<Slider>(); | |
ui.onValueChanged.AddListener(OnValueChanged); | |
comp = target.GetComponent(compName); | |
if (comp == null) | |
{ | |
Debug.LogErrorFormat("Component: {0} not found in {1}", compName, target); | |
return; | |
} | |
Type type = comp.GetType(); | |
BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; | |
field = type.GetField(propName, flag); | |
if (field == null) | |
{ | |
Debug.LogErrorFormat("Member: {0} not found in {1}", propName, compName); | |
return; | |
} | |
float value = (float)field.GetValue(comp); | |
ui.value = value; | |
} | |
protected override void OnDestroy() | |
{ | |
if (ui != null) | |
{ | |
ui.onValueChanged.RemoveListener(OnValueChanged); | |
ui = null; | |
} | |
if (comp != null) | |
{ | |
comp = null; | |
} | |
if (field != null) | |
{ | |
field = null; | |
} | |
} | |
void OnValueChanged(float value) | |
{ | |
if (field == null) | |
{ | |
return; | |
} | |
field.SetValue(comp, value); | |
if (label != null) | |
{ | |
label.text = string.Format("{0}: {1:0.0}", propName, value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment