How can I access GetComponentInChildren as string?

I want to access two Sliders on the same GameObject. Usually, I’d just use:

mySlider = GameObject.Find("myObject").GetComponentInChildren<Slider>();

However, I want to access one slider for music and one for soundFX. To distinguish the two, I thought that I’d try this method:

musicSlider = GameObject.Find("HUDCanvas").GetComponentInChildren("MusicVolume") as Slider;
musicToggle = musicSlider.GetComponent<Toggle>();
soundSlider= GameObject.Find("HUDCanvas").GetComponentInChildren("SoundFXVolume") as Slider;

It seems that we can’t use a string for “InChildren”.

The only other way that I can think of is to create an array, then loops through the array to find component by string. Is there a better solution or is this how you’d do it?

You can write an extension method gor game object to find a component in a child by name (or by tag which is faster). It could look like this:

    public static T FindComponentInChildWithTag<T>(this GameObject parent, string tag) where T : Component
        {
            Transform t = parent.transform;
            foreach (Transform tr in t)
            {
                if (tr.tag == tag)
                {
                       if(tr.GetComponent<T>!=null)                 
                             return tr.GetComponent<T>();
                }
                else //Find in GrandChildren
                {
                    T dummy;
                    dummy = tr.gameObject.FindComponentInChildWithTag<T>(tag);
                    if (dummy!=null)
                        return dummy;
                }
            }
    
            return null;
        }

Note: It’s generic, so you can use it for any component, not only slider. Plus it also searches for grandchildren. It you don’t need that stuff, you can remove it of course. You can use the extension method like this:

musicSlider=GameObject.Find("myObject").FindComponentInChildWithTag<Slider>("MusicVolume");