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:)).
----
![alt text][1]
-------
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().inventoryItemData = inventoryItemData;
instantiatedPrefab.GetComponent().SetIconUI();
}
}
}
![alt text][2]
-----
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;
}
}
[1]: /storage/temp/203778-screenshot-2023-01-11-at-134147.png
[2]: /storage/temp/203775-screenshot-2023-01-11-at-134417.png
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.
↧