Loving this, something has clicked

I am loving this course and something has clicked which I think its the way CodeMonkey teaches.

Anyway I am working on my buttons and have a basic question about this piece of code

    var unitActions = currentUnit.GetComponents<BaseAction>();
    List<Transform> buttonList = new List<Transform>();

    foreach (var action in unitActions)
    {
        var myButton = Instantiate(myButtonPrefab, transform); 
        myButton.GetComponent<ButtonBehaviour>().SetBaseAction(action);
        myButton.GetComponentInChildren<TextMeshProUGUI>().text=action.GetActionName();
        buttonList.Add(myButton);
    }
    buttonList[0].GetComponent<ButtonBehaviour>().HighlightButton();
    
    transform.GetChild(0).GetComponent<ButtonBehaviour>().HighlightButton();

What it does is highlight the first button green by calling this…

buttonList[0].GetComponent<ButtonBehaviour>().HighlightButton();

but if I try to do it with the following instead it doesn’t work?

transform.GetChild(0).GetComponent<ButtonBehaviour>().HighlightButton();

Any ideas?

What does happen when you run transform.GetChild(0).GetComponent<ButtonBehaviour>().HighlightButton();?

It’s not a guarantee that GetChild(0) will be the same as buttonList[0], depending on if the Transform already had children, or other possible factors.

1 Like

Yup like @Brian_Trotter said depending on how your hierarchy is set up the first index on the list might not be the first child. Perhaps the container already has some object placed on it before you Instantiate more.
You can test with a Debug.Log to see the object names

Debug.Log(buttonList[0]);
Debug.Log(transform.GetChild(0));
1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms