- Home /
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!
Answer by Waz · Aug 28, 2011 at 10:31 PM
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!
Your answer

Follow this Question
Related Questions
function overloading in Javascript 1 Answer
Behind the scenes voodoo w/ Instantiate 2 Answers
C# Question - Do I Have to inherit from MonoBehaviour? What happens if I don't? 2 Answers
How to make classes in C# that are assignable to public variables in scripts trough the Editor 1 Answer
C# Array of Child Objects 1 Answer