Ugui change sprite for dynamically created prefab

everything I find online is outdated and does not help this issue.

I have the following code

using UnityEngine;
using UnityEngine.UI;

public class InGameMainHudController : MonoBehaviour
{
    private GameObject buildMenu;
    private GameObject buildItem;
    private Sprite banana;

    public void Awake()
    {
        buildMenu = GameObject.FindWithTag("BuildMenu");
    }

    public void Start()
    {
        buildItem = Instantiate(Resources.Load("UI/BuildItem", typeof(GameObject)), new Vector3(10, 0, 0), Quaternion.identity) as GameObject; //inits a new buildItem Prefab and offsets it by 10 pixels
        buildItem.transform.SetParent(buildMenu.transform, false);  // adds it to the buildMenu panel
        banana = Resources.Load<Sprite>("UI/Img/banana");
      
        buildItem.transform.GetChild(0).gameObject.GetComponent<Image>().sprite = banana; //does nothing
    }
}

I’m trying to dynamically add a generic ui element that I’ve saved as a prefab and set it’s sprite.

I’m finding that I can’t do that there are methods for dynamically setting the sprite of a manually created game object, there are methods for dynamically creating a game object from script but no methods combining the two that I can see.

My prefab has one child panel which should be the one to receive the sprite.

how do I do this?

I tried this :

var child = buildItem.transform.GetChild(0).gameObject;
if (engy == null)
{
    Debug.Log("That is the problem");
}
else
{
    Debug.Log("its equal to this " + engy);
    if (child == null)
    {
        Debug.Log("That is the problem 2");
    }
    else
    {
        child.AddComponent<SpriteRenderer>();
        var childSprite = child.GetComponent<SpriteRenderer>().sprite;
        if (childSprite == null)
        {
            Debug.Log("That is the problem 3");
        }
        else
        {
            childSprite = banana;
        }
    }
}

I land on : “That is the problem 3”

I can’t GetComponent on child

The code is fine and should work as long as:
1 - Sprite “banana” is located in the “Assets\Resources\UI\Img” folder.
2 - the required Image component is on the first child of the prefab.

Not sure why you are checking the SpriteRenderer when in your example it is Image. And of course “.sprite” will be null for the newly added component … this is a meaningless check.

Check:
Debug.Log(Resources.Load<Sprite>("UI/Img/banana"));
Also, if you are sure that there is only one Image component in your prefab, then instead of
buildItem.transform.GetChild(0).gameObject.GetComponent<Image>().sprite = banana;
you can use
buildItem.GetComponentInChildren<Image>().sprite = banana;

1 Like