How to change the image of an instantiated prefab in the UI by mouse click on a game object in the scene?

Hello everyone,

Im working on an inventory for my simple hidden object game. I want to change the background of the icon in the inventory when I collect the hidden object in the scene (for instance when I collect the Jelly, I want to change the background of the jelly icon:)).



I collecting the objects with interface, which is attached to the game object.

Its looks like this:

using UnityEngine;
using System;

public class Jelly : MonoBehaviour, ICollectible
{
    public static event Action OnJellyCollected;

    public void Collect()
    {
        Debug.Log("You Collected The Jelly");
        OnJellyCollected?.Invoke();
    }

}

The inventory in the scrollview is populated by instantiating the icon prefab, with scriptable objects.

The Scriptableobject script:

using UnityEngine;

[CreateAssetMenu(menuName = "InventoryIcon")]
public class InventoryItemData : ScriptableObject
{
    public Sprite icon;
}

The following script is attached to the scrollview content:

using UnityEngine;

public class InventoryPopulator : MonoBehaviour
{
   
   
    public GameObject prefab;
    public Transform content;

    public InventoryItemData[] items;

    private void Start()
    {
        foreach(InventoryItemData inventoryItemData in items)
        {
            GameObject instantiatedPrefab = Instantiate(prefab);
            instantiatedPrefab.transform.SetParent(content, false);
            instantiatedPrefab.GetComponent<InvnetoryIconUI>().inventoryItemData = inventoryItemData;
            instantiatedPrefab.GetComponent<InvnetoryIconUI>().SetIconUI();
        }
    }
}


And this one is attached to the icon prefab:

using UnityEngine;
using UnityEngine.UI;

public class InvnetoryIconUI : MonoBehaviour
{
    public InventoryItemData inventoryItemData;

    [SerializeField]
    private Image icon;

    [SerializeField]
    private Image iconBackground;

    public void SetIconUI()
    {
        icon.sprite = inventoryItemData.icon;
        iconBackground.sprite = inventoryItemData.iconBackground;
    }

}

Can you please someone help me to implement the right code to change the icon background on collecting the scene object?

Any help is appreciated!

Thanks a lot.

Why are you trying to serialize the Images? You could just reference them through a script, so like in Jelly(), have

public InvnetoryIconUI ui; // You misspelled it, BTW
public InventoryPopular pop;

 public void Collect()
 {
     Debug.Log("You Collected The Jelly");
     // OnJellyCollected?.Invoke(); I don't know what event does
     ui.iconBackground.sprite = pop.items[1]; // for the jelly
 }

I hope it helps! If not, maybe try checking out B3agz’s “How to Make Minecraft in Unity” tutorial episodes 13 and 14, I think. He shows you how to make a FULL inventory system. It’s amazing.