How to get component value without using GetComponent() and Update()/FixedUpdate()?
How to get value of a component in a script that changes at runtime without using a GetComponent() and Update()/FixedUpdate()?
Example: during the game, user changed value of the slider by moving handle. How to get the new value of the slider in the script that the user has set?
public Slider slider;
public void OnButtonClick_GetSliderValue()
{
// how to get the new value of the slider which the user changed during the game ?
}
This case does not suit me:
public GameObject slider;
public void OnButtonClick_GetSliderValue()
{
float newValue = slider.GetComponent<Slider>.value;
}
,
Answer by GDGames0302 · Feb 13, 2021 at 07:30 AM
You can assign a function to a slider(something like OnValueChanged) just like you assign a function to a button. After you assigned this function(FunctionName) to the slider it will require you a Slider component, put the same slider on that empty slot. This way, that function will execute when you change the slider value and not every frame like in Update and that float will be equal to slider's value.
using UnityEngine;
using UnityEngine.UI;
public class ClassName : MonoBehaviour
{
public void FunctionName(Slider slider)
{
float newValue = slider.value;
}
}