1
\$\begingroup\$

I have a collectible item, which I can put into the inventory. Its GameObject has a InventoryItem script attached in which I want to set all parameters needed for correct display in the inventory. Here is the C# code:

InventoryItem.cs

public class InventoryItem : MonoBehaviour {
    public bool collectible = true;
    public string name;
    public Sprite sprite;
}

Part of ItemCollectingController.cs responsible of passing data to InventoryController

if (Input.GetButtonDown("Use")) {
    InventoryController inventory = GameObject.FindGameObjectWithTag("Inventory").GetComponent<InventoryController>();
    inventory.AddItem(target.GetComponent<InventoryItem>());
    Destroy(target);
    Debug.Log("Added to inventory");
}

And the important part of InventoryController.cs

public List<InventoryItem> items;
public void AddItem(InventoryItem item) {
    items.Add(item);
}

When collecting the item, the GameObject is destroyed and so is the reference in the InventoryController. The items List keeps a missing component. What can I do about that?

\$\endgroup\$
1
\$\begingroup\$

A Component must be attached to a GameObject. If you have data that needs to outlive its GameObject, then it should not be built into a Component.

Consider instead creating your inventory items as ScriptableObjects - these are persistent data objects that live in your assets folder. You can still edit them in the inspector, but they have an identity of their own not dependent on any particular GameObject or Scene.

eg.

// This line lets you create items via the right-click / Asset -> Create menu
[CreateAssetMenu(filename = "NewItem", menuName="Inventory Item")]
public class InventoryItem : ScriptableObject {
    public bool collectible = true;
    public string name;
    public Sprite sprite;
}

Then to attach this to an in-world collectible, make a distinct component for the GameObject that houses it:

public class CollectibleItem : MonoBehaviour {
    public InventoryItem item;
}

Now when you collect the item, you can ask the CollectibleItem component to tell you which item archetype to add to your inventory. Once it's done that, you can destroy the CollectibleItem along with its GameObject safely - it just held a reference to the InventoryItem, but that item can keep living on after the collectible is gone.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.