- Home /
how to link variable as inspector field
i want to implement a slider UI component which changes the value of another script on interaction.
p.e. i have a component Component
with public float a
.
and i have a sliderUI component SliderComponent
which changes this variable based on the Input.
so onEnable the SliderComponent goes
sliderValue = Component.a
and on Change / Input it goes
Component.a = sliderValue;
but i want to reuse this component for multiple variables / sliders. meaning i want Component.a
to be dynamic and assigned in the Editor / inspector.
how can i make this target an inspector property?
Overall i want similar inspector behavior to how functions are selected for UnityEvents.
But i dont know any way to pass a dynamic value into those functions / use the return value
Answer by Hellium · Jun 24, 2018 at 11:50 AM
If I understand you right, you want a two ways binding between your slider and the variable of your class?
Here is how I would do it:
[System.Serializable]
public class FloatEvent : UnityEngine.Events.UnityEvent<float> {}
private float a ;
// Attach the setter to the `onValueChanged` event of the slider
public float A
{
get { return a ; }
set
{
if( !Mathf.Approximately( a, value ) )
{
a = value ;
onAValueChanged.Invoke( a ) ;
}
}
}
// Attach the `value` setter of the slider to the `onAValueChanged` event of the script
[SerializeField]
private FloatEvent onAValueChanged;
nice!
i now use a setter function public set(float)
in the other script and put it into the UnityEvent.
this synchronizes the slider variable to the script. perfect!
but as far as i understand, this is only one way binding?
is it possible to read the variable in the beginning to set the slider?
In the onValueChanged
event of the slider, if you provide the setter, you have a one way binding : slider → value
In the onAValueChanged
event of the script, if you provide the value
of the slider, you have the 2nd binding.
is it possible to read the variable in the beginning to set the slider?
Yes, you can call the event in the Start
method
void Start()
{
onAValueChanged.Invoke( A ) ;
}
i noticed that the Slider value
is listed as dynamic float
how can i create such dynamic floats in other scripts?
the public floats in my other scripts are not listed / selectable in this UnityEvent type.