Trouble with Scriptable Objects and How to create new ones in functions

Hey guys, so I am making a game using scriptable objects as containers for item information (basically, they don’t need to be game objects since they wont ever exist in the world, I only need the stats like damage that they have to modify the character’s battle stats). However, I’m running into a snag when trying to create a function to automatically add any scriptable object item to a character’s inventory!

protected BaseStatsWeaponItem[] characterWeaponInventory = new BaseStatsWeaponItem[4]; /* array of weapon items (max of 4 per toon) */

I created a basestats weapon item from which all weapons inherit, which itself inherits from a universal baseitem scriptable object, so I created an inventory array to hold weapons

However, this function is giving me trouble:

public void AddWeaponToInventory(int weaponToBeAddedID)
    {
        BaseStatsWeaponItem newAddedWeapon;
        for (int i = 0; i < this.GetComponent<MainGameData>().listOfWeapons.Count; i++)
        {
            if (this.GetComponent<MainGameData>().listOfWeapons[i].ItemID == weaponToBeAddedID)
            {
               
                newAddedWeapon = ScriptableObject.CreateInstance<this.GetComponent<MainGameData>().listOfWeapons[i]>(); //problem is in this if statement
            }
        }
       
        if (newAddedWeapon.GetType().IsAssignableFrom(typeof(BaseItem)))
        {
            if (newAddedWeapon.GetType().IsSubclassOf(typeof(BaseStatsWeaponItem)) && this.CharacterWeaponInventory.Length < 4)
            {
                int slotToBeAddedTo = this.CharacterWeaponInventory.Length;
                this.CharacterWeaponInventory[slotToBeAddedTo] = newAddedWeapon;
                this.EquippedWeapon = this.CharacterWeaponInventory[0];
            }
        }
    }

I figured that having a list of the scripts of the scriptable objects in my main game data script (not attached), would make it easier to sort through all the weapon scripts and find the one that matches. I was hoping to be able to say, “oh you clicked this spot in the shop that corresponds with this id”, therefore “if you have enough space in your inventory we will add a new instance of this weapon to your inventory”. Thanks in advance, and let me know if anything is unclear, I’ve been reading a lot about scriptable objects but the information doesn’t necessarily cover what I am trying to do exactly

All right… I just finished reading your post and possibly glazed over an important point… What was the trouble? lol

Okay, sorry on another note: Have you considered using the scriptable objects solely as references and not creating new ones for the inventory?

My trouble is just that it doesn’t work, gives me errors when I try to directly plug in the type to the createInstance and when I try to store the type in a variable first, then plug in, it still gives me errors. I thought about that, but I thought that since each character would have their own, it would make sense to instantiate one for each separate character? That way, since the items have durability, each character would be reducing the durability of their own specific copy of each item? If i understand how scriptable objects work correctly

CreateInstance can take a string or type… I was thinking maybe because you didn’t have the type (because for sure it wouldn’t work as you posted).
but you said you did try with a type, and that didn’t work.
You could maybe try .GetType()

however… I can see what you mean about durability, maybe… I saw someone give this reason once before, too. I guess it’s up to [us] how we use them.
Depends on how complex your setup is.
Is durability the only degrading feature?
You could have a wrapper script with : Durability and the ScriptableObject reference.
:slight_smile:

Hmm, I guess I understood this CreateInstance wrong! So you’re saying that I can pass in a string as a a parameter for my weapon function and that if that parameter matches up with the name of, say a weapon class that I created, i could create a new instance of that class that way? That is something I could work with if that’s the case

Well, it takes Type or string it says in the docs.

This is a Generic Function

CrateInstance<WeaponType>();

the code thats calling this function needs to know, at compile time, what exact type you want the instance to be.

This is not a generic function

CreateInstance(Type typeName);

this also allows you to specifiy the type of scriptableObject instance you want. Its more dynamic you don’t need to know the type at compile time. however its more vulnerable to the input you give it. in that they won’t catch as many errors at compile time. plus its a tad slower. BUT it is more dynamic which is what you need. just make sure you validate that you have the right type before calling CreateInstance.

also cache your getComponents your functions will run faster

    public void AddWeaponToInventory(int weaponToBeAddedID)
    {
        BaseStatsWeaponItem newAddedWeapon = null;
        Type weaponType;

        var gameData = GetComponent<MainGameData>();
        if(!gamedata || gamedata.listOfWeapons == null) return;

        var listOfWeapons = gamedata.listOfWeapons;
        int count = listOfWeapons.Count;
      
        for (int i = 0; i <count; i++)
        {
            if (listOfWeapons[i].ItemID == weaponToBeAddedID)
            {
                if(!(listOfWeapons[i] is BaseStatsWeaponItem))
                {
                     Debug.LogWarningFormat("Weapon '{0}' is not of type BaseStatsWeaponItem", listOfWeapons[i]);
                     continue;
                }

                weaponType = listOfWeapons[i].GetType();
                if(!weaponType.IsSubclassOf(typeof(BaseStatsWeaponItem)
                {
                    continue;
                }

                newAddedWeapon = ScriptableObject.CreateInstance(weaponType);
                break;
            }
        }
    
//  this code is uneeded if BaseStatsWeaponItem derives from BaseItem as you say
//        if (weaponType.IsAssignableFrom(typeof(BaseItem)))
//        {
            if ((bool)newAddedWeapon && this.CharacterWeaponInventory.Length < 4)
            {
                int slotToBeAddedTo = this.CharacterWeaponInventory.Length;
                this.CharacterWeaponInventory[slotToBeAddedTo] = newAddedWeapon;
                this.EquippedWeapon = this.CharacterWeaponInventory[0];
            }
//        }
    }

Awesome, I ended up getting it to work, thanks Joshua and methos, you guys definitely helped my understanding of scriptable objects a lot! Have a great day guys

Cool, you too :slight_smile: