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!");
}
}
}