Dynamically Adding Scripts to items in inventory

ElRafaVaz

New member
Hi everybody,

I'm looking for a way to add monobehaviours on the creation of items in the inventory. I'm working on a game that includes synergies between items in the inventory (in the same vein of Backpack battles https://playwithfurcifer.itch.io/backpack-battles ) and the easiest way to do this is to be able to have my own scripts attach to items in the inventory.

At first I thought this was the purpose of the 'codebase' item attribute definition, but after some experiments I realized this is not the case. I also thought about using the ItemObject script, but this seems to be made to link objects in th inventory with gameobjects outside of it, while I'd like to have control of the gameobject inside the inventory.

Is there any way to do this?

In advance, thank you.
Rafa
 
You cannot add Monobehaviours on Items within the Inventory. Because Items are simple C# classes, not gameobjects.
When an item is spawned (pickup, equipment, etc...) Then we link a gameobject with an Item via an ItemObject component. That's when you can indirectly add Monobehviours to your item.


You should consider items purely as data. no logic. It's good practice to seperate data from logic in general.

So for your use case there are two ways you could go about this.

1. Make a custom class that you could call "ItemSynergyData". And you could add this class as an ItemDefinition attribute.
In there you could define all the possible synergy types with properties for values.

Then in the UI you would add you Monobehaviour with the logic. Each time an item is added in the Inventory you would listen to that event and loop through your items and their position in the UI. Then you would check their synergy data and compute whatever needs to be computed.

2. If you want each item to have a completely different synergy logic, then I might recommend using ScriptableObjects to hold your logic and set those as ItemDefinition Attributes on your item. we could call this attribute "ItemSynergySO"

Then you could loop through all your items and call a function on the ItemSynergySO where you can pass it all the item positions and the current item. This way it can compute whatever it needs to compute.

It's not really the same use case, but some information here might be worth the look.
Check this out: https://opsive.com/support/documentation/ultimate-inventory-system/item/item-skills/


You could also make a mix of option 1 and 2.

Note that what you are trying to do isn't something trivial. It will require careful consideration and a fair amount of code, no matter what direction you go with.
 
Top