I’m trying to learn scriptable objects but I’m running into problems with the data disappearing when I create an instance.
A little background. I’m using Scriptable Objects to create an inventory system. At startup I read in and create an instance of the needed items. Then for actions like stack splitting I create a copy of the object. The problem is that the copy doesn’t retain any data in the fields (everything is null) so I’m forced to write a bunch of code to populate the variables in the copy. Example:
Thanks, I’ll see if this fixes the issue I’m having.
What I really want is for all of the items to read back to the same scriptable object. For example, a character can equip 2 of the same sword, instead of each sword having its own set of identical data, I just want a reference to the original scriptable object. That would be ideal. Will Instantiate() do that for me?
No, Instantiate will make copies of scriptable objects. They will be their own UnityEngine.Objects distinct from one another.
What you want to do is make a serialisable plain class that wraps around your scriptable objects. The plain class holds the unique data, and also a reference the the actual scriptable object item. The item’s data should remain immutable.
In my own project I have the following structure:
|- ItemListing (wrapped item + quantity of item)
|-- ItemWrapper (serialisable class that wraps around an item SO)
|— ItemBase (the actual item SO)
I only care about quantities of wrapped items. And any access to an items data should be done through the wrapper, which serves as an intermediately between the outside and the item’s data.