Polymorphism and ScriptableObjects

Hello, I’m having an issue with passing scriptable objects to methods in another class, which is causing nullreferenceexceptions.

Fisrt, here is the structure of my classes:

I have a Item class deriving from ScriptableObject, and Weapon class that derives from Item, a weapon, VSPR which derives from the Weapon class, an Inventory Class that derives from ScriptableObject and a Player class.

Here is the code in my Inventory Class:

public SBVPlayer owner;

public List<SBVItem> itemInventory;

public List<SBVWeapon> weaponInventory;



			

public void AddItem(SBVItem item)

{

	itemInventory.Add(item);

}



public void AddItem(SBVWeapon weap)

{

	Debug.Log(weap);

	weaponInventory.Add(weap);

}

From my player class, I am instantiating an Inventory and Weapon, which gets passed to the inventory’s AddItem method like so:

		inventory =  ScriptableObject.CreateInstance("SBVInventory") as SBVInventory;

		inventory.AddItem(ScriptableObject.CreateInstance("VSPR") as VSPR);

So, this gives me the following error:

NullReferenceException: Object reference not set to an instance of an object
SBVInventory.AddItem (.SBVWeapon weap) (at Assets/Scripts/Core/SBVInventory.cs:26)
SBVPC.Start () (at Assets/Scripts/Core/SBVPC.cs:99)

However, the Debug.Log in the AddItem method works fine, and prints “VSPR”

I’m not sure if the problem is due to polymorphism or if I’m making a mistake. Any help would be appreciated. Thanks!

1 Answer

1

You haven’t initialised weaponInventory. I.e.

weaponInventory = new List<SBVWeapon>();

same for your other list.

Thanks. Sometimes it's the little big things that get me!