How to Access Slider through code

hi,

i am working on a game where on start everything is instantiated.

one of my objects is a slider should be connected to a script on one of the objects.

on start i want to place the slider from the Main Camera(Clone) into the Slider slider of the script of the game object which requires the sliders use.

also i need to make the slider function access this script. i need to set the game object in the slider and choose the function. which i do not know how to do through code…

i know how to do this if everything is already in the scene but they are being instantiated instead so the values are null…

When you instantiate a GameObject you will receive a reference to that newly-created GameObject.

For instance, if this is your prefab:

public GameObject MyPrefab;

then later in your code when you instantiate it:

GameObject go = Instantiate<GameObject>( MyPrefab);

At that point the variable called ‘go’ points at that new instance. I recommend a better variable name than ‘go’ obviously.

Now you can use go.GetComponent() to find the Slider on that GameObject, then assign it to another script:

Slider slider = go.GetComponent<Slider>();

hey thanks for the reply,

ive been trying allot to get the slider… its just not working… i have done it exactly as you wrote but it is not filling Slider slider…

the canvas which holds the slider is a child of the mainCamera… does that make a difference?

i wrote the code: i was able to retrieve the mainCamera GameObject, then in a different variable Slider slider i wrote:
slider = mainCamera.GetComponent();

still did nothing…

i was finally able to retrieve the slider using the code:

slider = (Slider)FindObjectOfType(typeof(Slider));

not i just need to add the function to the slider… add the gameobject then set function to the dynamic slider control…

1 Like

slider.onValueChanged.AddListener(ListenerMethod);
public void ListenerMethod(float value)
{
}

Took me a long time to figure out why I couldnt access the Slider through code.
Apparently I had been trying to use

using UnityEngine.UIElements
instead of
using UnityEngine.UI”.

Changing that solved all my problems.

6 Likes