How to add "Properties" to items?
Say I have an item class, and I'd like to add properties to each item. For example, one item could have the "sharp" attribute, another could have the "blunt" attribute, say a water bottle could have the attribute "water" and etc.
If you have played the STALKER CoP misery mod, you will know what I am talking about. Say I want to clean my weapon, and there is an item that has the "cloth" attribute. I can use said item to add a small repair bonus.
What would be the best way to go about doing this?
Answer by StephanT · Feb 12, 2016 at 01:51 PM
Write a script and attach it to all items which should have attributes.
In that script, define a public static enum with your desired attributes. I call it 'Types'. Each script should have a public variable of that enum type to identify a certain instance. I call it 'attribute'.
So you can check like this:
var attributeScript = item.GetComponent<Attribute>();
if (attributeScript != null & attributeScript.attribute == Attribute.Types.SHARP) {
// sharp item found
}
Additionally, you could make Attributes contain a list or an array of those enum values so you can have multiple attributes per item without having to attach many scripts to a prefab.
If you are familiar with bit masks or willing to learn bitwise operations you have more options and can make this super performant. You could use the [Flags] attribute on that enum and store the attributes as bits of an integer. Or if you have more attributes than can fit in an int, use the BitArray class
Your answer
Follow this Question
Related Questions
RPG Picking up items with polymorphism - probably quick :) 1 Answer
Move Object to Players Hand 0 Answers
Argument out of range? 2 Answers
How to make an Inventory Hotbar (C#) 0 Answers
Raycast on mouse position problem. how not to raycast to 0 1 Answer