Created
March 16, 2018 05:30
-
-
Save asus4/fb6483e89f70a039f8397b1c15ebc485 to your computer and use it in GitHub Desktop.
[Unity] Bind the slider value into a private float serialize field in any MonoBehaviour.
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