- Home /
How to create a deep copy of a Prefab?
I'm having an issue where I have a component called Item which holds an ItemData variable in it, which represents the "internal state" of the item, including a reference to its prefab.
When I add a ItemData to an inventory (array), it copies the ItemData like this and then places the copy into the array/inventory:
public ItemData(GameObject prefab, string name, string description)
{
this.prefab = prefab;
this.name = name;
this.description = description;
}
And then the original Item GameObject is destroyed, however it seems that this.prefab = prefab
doesn't actually copy it, because when i run it, the prefab variable in the copied ItemData is null. Which results in bad things when I try to try to instantiate it (which I for example do when I drop the item from the inventory)
So how would I actually copy the prefab and not reference it?
Depends. Do you want a copy of the prefab as another prefab, or as a temporary gameobject used during game time?
I want a copy of the non-instantiated prefab.
What's the exact use case of this? Because either you assign the differences between your items on instantiate, that's when it matters for the game, or you create a copy as a prefab for some other uses. The whole purpose of a prefab is being copied when needed, by instantiating one. What use do you have for that somewhat redundant copy?
Answer by victorbisaev · Jan 28, 2018 at 09:38 PM
"GameObject" is a reference, so if you put a reference to the original Item into an array item and then remove the original Item, the reference becomes not non-valid. So either you should keep the original Item and use it as "Original" template for all instantiated items from your inventory, or the "prefab" field should reference a prefab from your Project (which is always available for instantiation).
The original GameObject is always there since it is a prefab and cannot be removed.
I think my problem happens when the ItemData gets copied and moved into the inventory array. I don't think it actually copies the GameObject variable in it, which points to the prefab, but actually references that variable. So when it is copied and the object which I copied from is destroyed, the copy's GameObject variable is no longer valid due to the fact that it was referencing the variable to the prefab and not the prefab itself.
I have no idea if that makes any sense at all, if not I think I might have to paste the actual code.
Ok, then maybe you could give more information on how "when the ItemData gets copied and moved into the inventory array" happens?