I know how to find the slider itself but i don’t know how to change that thing the arrow is pointing to during run time with a script using c#. I want it to reference to an object but not through the inspector, through script. This is the closest i can get but am stuck.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Block_Change_Behavior : MonoBehaviour {
public GameObject slider;
void Start () {
slider = GameObject.FindWithTag ("slider");
}
OnMouseDown() {
slider.GetComponent<Slider> ().onValueChanged.AddListener(this);
}

Adding a gameobject in the inspector is purely only to list a bunch of functions that can be accessed on that gameobject. You don’t need to do that in code. With the .AddListener()
function you only need to pass in the function that you want to be called when the slider value has changed.
Because the UnityAction
in this case also passes a float as a parameter so the callback function needs to also have that parameter. .AddListener(DoSomething);
void DoSomething(float sliderValue)
{
// do stuff here
}
If you dont want it to have the parameter you can use lamda expressions
.AddListener((s) => DoSomething());
Its also worth noting that this callback function can be anywhere, even from another script. So you could do something like .AddListener(otherScript.DoSomething)
Also you shouldn’t add a listener every time you press the mouse button down… you should only add your listeners once. In the Start()
generally.
You’re script should look something like this:
public class Block_Change_Behavior : MonoBehaviour
{
public Slider slider;
void Start()
{
slider.onValueChanged.AddListener(OnSliderValueChanged);
}
void OnSliderValueChanged(float sliderValue)
{
Debug.Log(sliderValue);
}
}