Cloning Scriptable Items

I have tried a lot of different ways, but haven’t found one that works so here I am.

Current code works, but it uses the original scriptable Object instead of creating a clone. The clones needs to have the same vars and values as the Originals

 static void LoadItems()
    {
            Object[] Items = Resources.LoadAll("ScriptableObjects/StoreObjects/", typeof(Item));

            foreach (Item i in Items)
            {
                Item item = ScriptableObject.Instantiate(i);
                ItemDatabase.Add(item);
            }
            Debug.Log("Items in database: " + ItemDatabase.Count);
    }

What it does

  • Load all items from Resource folder
  • Adds the orginal Scriptable Object into the database

What I want the code to do:

  • Load all Scriptable Objects from Resource folder
  • Make a copy of the Scriptable Objects and add them to the ItemDatabase List.

What makes this hard:

  • Item is a parent class.
  • it has child classes like: Harddisk, Server…
  • The Script that holds the itemdatabase is a public static.

You are making a clone when you call Instantiate though. Also, all ScriptableObjects are “copies” in builds so are you certain you actually need to copy them in the first place? It should be fine as long as your data is immutable.

if I look at the original Scriptable Object in resource folder, it changes the values when I change the clone’s values ingame. Pretty sure that wasn’t the case in earlier project when I managed to create a real clone without static and all that.
Not sure what Immutable means, but if I start my project for example and do changes to the scriptable object in play mode, then stop playmode the values will stay have saved the changes automatically.

Follow up:
I tried

 public void AddTestObjects()
    {
        foreach (Item item in GlobalVars.ItemDatabase)
        {
            Inventory.Items.Add(Instantiate(item));
        }
    }

still the same result. Doing a edit to scriptable object ingame also changes value to original one.

Facepalm
erhm… I figured it out - all scripts above works as it should - the mistake is that one of objects I use had the SO directly in the inspector, and that is why the values was changed after play testing… :slight_smile:

1 Like