Trouble using GetComponent<Image> in parent class of a button prefab.

I wasn’t expecting this. Here is my code:

        int x = 50;
        int count = 0;
        foreach(Sprite thisSprite in GameTileSprites)
        {              
            TextureButton newButton = Instantiate(TextureButton, new Vector3(x, 68.8f, 0), Quaternion.identity) as TextureButton;
            Image buttonImage = newButton.transform.GetComponent<Image>();
            buttonImage.sprite = thisSprite;
            newButton.transform.SetParent(panelTextureImages);
            newButton.ElementIndex = count;
            x += 90;
            count += 1;
        }

If I instantiate as TextureButton, then I cannot obtain the Image component from the Button subclass. If I instantiate as a Button, then I cannot access the ElementIndex property of the superclass. I was under the impression that GetComponent would obtain any component within the complete gameobject. Tips? Solutions?

Did you make sure to add a reference to the UnityEngine.UI?

using UnityEngine.UI;

8 Likes

While I had that problem about a week ago that is unfortunately not the solution to this problem. Thanks for the response though.

Maybe try parenting your object to a canvas before you try getting the image component? Btw, not related, but the following code:

newButton.transform.GetComponent<Image>();

can simply be:

newButton.GetComponent<Image>();

No need to dig into transform first. You can get any component from any component.

1 Like

Yes, GetComponent should return any component on the GameObject in question.

Things to check:

  • Make sure the Image component is actually on the same GO as the TextureButton component, and not on a child
  • Make sure you’re instantiating the correct prefab
1 Like

Thanks again for your responses. I ended up solving it with the following code:

void DisplayGameTileTextures()
    {
        int x = 50;
        int count = 0;
        foreach(Sprite thisSprite in GameTileSprites)
        {       
            TextureButton newTextureButton = Instantiate(NewTextureButton, new Vector3(x, 68.8f, 0), Quaternion.identity) as TextureButton;
            newTextureButton.ElementIndex = count;
            newTextureButton.transform.SetParent(panelTextureImages);
            TextureButtons.Add(newTextureButton);

            Image buttonImage = newTextureButton.gameObject.GetComponent<Image>();
            buttonImage.sprite = thisSprite;

            x += 90;
            count += 1;
        }
    }