0
\$\begingroup\$

Here is a function I call out am UI element:

public void LoadCurrentItem(ItemType t)
{
    List<Item> itemList = SessionManager.singleton.GetItemAsList(t);

    if (itemList == null)
        return;
    if (itemList.Count == 0)
        return;
    GameObject prefab = (t == ItemType.consumable) ? eq_left.inventory.slotTemplateUD : eq_left.inventory.slotTemplateLR;
    Transform p = eq_left.inventory.slotGrid;

    int dif = iconSlotCreated.Count - itemList.Count;
    int extra = (dif > 0)?dif: 0;

    for (int i = 0; i < itemList.Count + extra; i++)
    {
        if (i > itemList.Count -1)
        {
            iconSlotCreated[i].gameObject.SetActive(false);
            continue;
        }

        IconBase icon = null;
        if(iconSlotCreated.Count -1 < i)
        {
            GameObject g = Instantiate(prefab) as GameObject;
            g.SetActive(true);
            g.transform.SetParent(p);
            icon = g.GetComponent<IconBase>();
            iconSlotCreated.Add(icon);
        }
        else
        {
            icon = iconSlotCreated[i];
        }

        icon.gameObject.SetActive(true);
        icon.icon.enabled = true;
        icon.icon.sprite = itemList[i].icon;
        icon.id = itemList[i].item_id;
    }

}

It might seem less informative, but my question is simple and stupid: I want to destroy my GameObject g that instantiates prefab before it instantiates prefab so that I can refresh GameObject g to create eq_left.inventory.slotTemplateUD or eq_left.inventory.slotTemplateLR

How can I achieve this goal?

\$\endgroup\$
3
  • \$\begingroup\$ why do you want to destroy the GameObject before it creates another GameObject? \$\endgroup\$
    – i.do.stuff
    Mar 12, 2019 at 19:10
  • 1
    \$\begingroup\$ I think you want to destroy a previously instantiated game object when this function is called a second time, is that right? \$\endgroup\$ Mar 12, 2019 at 19:45
  • \$\begingroup\$ Yes, I do want to destroy the previously instantiated game object second time, is there any way ?? \$\endgroup\$ Mar 13, 2019 at 2:32

1 Answer 1

3
\$\begingroup\$

Just store a reference to your instantiated object and check if it is != null when you want to create a new one. Then destroy the old one. Try something like this:

private GameObject someObject;

private void SpawnObject()
{
    if(someObject != null)
    {
        Destroy(someObject);
    }
    someObject = Instantiate(yourPrefab);
}

Of course to minimize perfomace losses by instantiating on runtime I would suggest you implement some sort of ObjectPool for that.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .