So Interestingly, I already have working code to modify source images for other UI elements, but when I tried to do the same thing with buttons for an inventory bar it didn't work. When the code runs, it doesn't change the image, but doesn't give any errors.
The main difference I can see is that The original script was attached to the Object it was modifying, but I really don't see how that will affect anything.
Original code (not full code, it's pretty long with other unrelated stuff):
public GameObject healthUI;
public Sprite Health_3;
public Sprite Health_2;
public Sprite Health_1;
public void ChangeSprite()
{
if (thisobjecthealth == 3)
{
healthUI.GetComponent<Image>().sprite = Health_3;
healthUI.GetComponent<RectTransform>().anchoredPosition = new Vector2(-269.12f, 170.8f);
healthUI.GetComponent<RectTransform>().sizeDelta = new Vector2(166.152f, 50f);
}
if (thisobjecthealth == 2)
{
healthUI.GetComponent<Image>().sprite = Health_2;
healthUI.GetComponent<RectTransform>().anchoredPosition = new Vector2(-300.1048f, 170.8f);
healthUI.GetComponent<RectTransform>().sizeDelta = new Vector2(104.1824f, 50f);
}
if (thisobjecthealth == 1)
{
healthUI.GetComponent<Image>().sprite = Health_1;
healthUI.GetComponent<RectTransform>().anchoredPosition = new Vector2(-324.2041f, 170.8f);
healthUI.GetComponent<RectTransform>().sizeDelta = new Vector2(55.9838f, 50f);
}
if (thisobjecthealth < 1)
{
healthUI.GetComponent<Image>().enabled = false;
}
if (thisobjecthealth > 0)
{
healthUI.GetComponent<Image>().enabled = true;
}
}
now my other code:
public class Inventory : MonoBehaviour
{
// Start is called before the first frame update
public int[] inventory = new int[8];
public Sprite gun;
public GameObject slot1;
public GameObject slot2;
public GameObject slot3;
public GameObject slot4;
public GameObject slot5;
public GameObject slot6;
public GameObject slot7;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (inventory[1] == 1)
{
slot1.GetComponent<Image>().sprite = gun;
Debug.Log("Change!");
}
}
}
GetComponent<>()
finds a component attached to the same game object that your script is attached to. If the image component is not part of the game object your script resides on, you'll have problems.Edit: your script calls
gameObject.GetComponent<>()
, which is fine. This is not the cause of your issue, but it's still good practice to avoid callingGetComponent<>()
frequently.Instead, use a serialized field just like you did for the list of game objects in the inventory class. If you need a field to be private, you can mark it with a
[SerializeField]
attribute to make it show up in the inspector like public fields do.As a little bonus, caching the reference to the image will save on performance in comparison to running
GetComponent<>()
every time you change its properties. Unity has to comb through every component on the game object every time you call the function!