V
V
Void592022-03-26 21:20:40
C++ / C#
Void59, 2022-03-26 21:20:40

How to make a function call when a variable changes in Unity?

Good evening! I'm making sound settings for the game in Unity. I want to make the volume change function triggered by moving the slider (in fact, by changing the variable). How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
K0TlK, 2022-03-26
@Void59

If the slider is a unit slider, then it has an onValueChanged event. You subscribe to this event a method that changes the volume and that's it.
Something like this:

[SerializeField] private Slider _slider;

private void OnEnable()
{
    _slider.onValueChanged.AddListener(ChangeVolume);
}

private void OnDisable()
{
    _slider.onValueChanged.RemoveListener(ChangeVolume);
}

private void ChangeVolume(float amount)
{
    //изменить громкость на значение amount
}

V
Vasily Bannikov, 2022-03-26
@vabka

Change the variable only in one place (in some method)
And call the desired function in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question