- Home /
A way to implement "Use" of item in game. A way to serialize object with method from other script maybe?
So I'm making simple inventory system. My approach is this. I got class Item with bunch of fields. I store them in a list itemDatabase inside of ScriptableObject itemDatabaseAsset. I want to assign effects of items in the editor. One of my ideas was this
[System.Serializable] public class Item {
public string itemName;
//some more variables
public Effect itemEffect; // Custom class effect.
//some more code
public void Use(Entity x) // Method "Use" called from inventory
{
itemEffect.UseEffect(x); // It calls virtual method "UseEffect" of "Effect" custom Class.
}
}
Then i have all the effect classes i want dirived from "Effect" class and i just assing it in editor like
Item_Database_Asset.Items_Database_List[1].itemEffect = new TestEffect(); // Item 1 from database had assing TestEffect with ovveriden UseEffect function.
This didn't work because apparently unity doesn't support polymorphism when serializing, which means after deserialization all me different effect becomes base Effect class they all derived from. However, if i do the same assigning TesetEffect to Item on runtime it works(duh). So i got 2 ideas is there a way to refer a method to an item in an editor, so on run time it's assigned itself by that refer. Or maybe just store a name on effect(string) and invoke it by name(GetMethod(string) or something i don't know. The latter seams a bit weird or it's ok? Thank you.
I'm making a game and going to make a simple inventory interface. You question scared me, is it necessary to mess with classes so much? :)
Answer by eggorko · Aug 18, 2017 at 10:14 AM
Well, i tried my second idea and it worked. I give item string EffectName in editor and on run-time just loop through all items in database list and do GetMethod(EffectName) stuff. It's also involves Delegate.CreateDelegate function which i just found out exist and it's awesome. I will write the whole shebang later here. But i'm also need some feedback. Is't it an overkill? There must be much pimplier way to do this.