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