- Home /
Getting a copy/clone of an object from an array (C#)
I'm currently working on an inventory and item management system that uses a sort of loot table system for all possible items. The loot "table" is quite simple, it's just an array of my InventoryItem objects that I want to define in the Inspector. Hypothetically, if I wanted to add one of those items to my player's inventory, through some sort of function like this:
inventory.AddItem(lootTable[1]);
It would just pass the reference to the same object in memory, so both my inventory class and my loot table class would be pointing at the same object. Is there an easy way to clone that object, short of making an entirely new function to copy all the parameters to a new one?
Or, if there's a better way to implement a loot table like this I'm all ears.
What are the entries of 'lootTable' if they are game objects or components on game objects, you can just use Instantiate() to make a copy.
lootTable
contains InventoryItem objects (C# objects, not GameObjects or Components).
They contain all the information needed to make a GameObject and its Components (say, if the item was dropped into the world and we need to create a GameObject), however they don't have the ability to create that GameObject. They also do not extend $$anonymous$$onoBehaviour.
$$anonymous$$y usual solution to this situation is the thing you are trying to avoid. I add a Copy() method to the InventoryItem class and do:
inventory.AddItem(lootTable[1].Copy());
Yeah, I wouldn't be surprised if that's what I'll end up doing. I'm messing around with C#'s $$anonymous$$emberwiseCopy(), which does a shallow copy and may be suitable for my needs. If it works, I'll post it as an answer.
Answer by rgowen · May 16, 2014 at 03:20 AM
Answering my own question:
I ended up using C#'s MemberwiseClone() for this. It works fine for what I need. You should read how it works before implementing it yourself, as it is a shallow copy and will duplicate only the references to other objects within the object being cloned.
Thanks for answering your own question. I learned something I'll use in the future.