Notice: Since Unity 2021, this check will result in Unity throwing an error, do not use this
So I discovered a potential “bug” in the code for randomly generating the UUIDs in InventoryItem… If you Duplicate an InventoryItem in the inspector, the UUID for both items will be the same. When you go to retrieve an item, the GetFromID() method will complain about two (or possibly many more) items with the same UUID, and you’ll only be able to retrieve one of the items… even if all three items were saved somewhere…
Fortunately, there’s a solution, though it will require the help of Linq
Add this to your usings clause: using System.Linq;
Then in the ISerializationCallbackReceiver.OnBeforeSerialization() change your method to look like this:
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
// Generate and save a new UUID if this is blank.
if (string.IsNullOrWhiteSpace(itemId))
{
itemID = Guid.NewGuid().ToString();
}
// Test for multiple objects with the same UUID
var items = Resources.LoadAll<InventoryItem>(""). //continues below
Where(p => p.GetItemID() == itemID).ToList();
if (items.Count > 1)
{
itemID = Guid.NewGuid().ToString();
}
}
What this does, in a nutshell, is query the Resources, basically “give me a list of every InventoryItem with this itemID and put it in a List for me”. It’s a magical Query device that System.Linq provides.
The object you’re editing is one of those objects. If there is a duplicate object, then items.Count will be greater than 1. If this is the case, then we change the UUID. If the count is 1, then there is no need to change the UUID of the item.