I have an item inheritance chain that goes something like.
Item → Food → CanOfBeans.
//item.js
#pragma strict
public class Item {
var itemName : String;
var invCategory : String;
var itemWeight: float;
}
public class Food extends Item {
var numUses: int;
var recoverHunger : int;
}
public class Weapon extends Item {
var ammo : int;
}
/*************************************************FOODS*************************************************/
public class CanOfBeans extends Food {
var itemDurability : int;
}
/************************************************WEAPONS************************************************/
public class Beretta9mm extends Weapon {
var weaponDurability : int;
var weaponDamage : int;
}
Each item has their own Script attached to them. Items have an obj of their type attached to them. I call function AddItem and Add them to the list.
//ItemManager.js
#pragma strict
import System.Collections.Generic;
public var weight : float;
public var maxWeight : float;
var invList : List.<Item> = new List.<Item>();
function Update () {
if (Input.GetKeyDown ("f")) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit)) {
if (hit.collider.tag == "Item"){
hit.collider.gameObject.SendMessage("AddItem");
}
}
}
}
//CanOfBeansAtt.js
//Attached to Prefab "Can of Beans"
#pragma strict
public var itemObj : CanOfBeans;
public function AddItem() {
var x = GameObject.FindGameObjectWithTag("Manager").gameObject.GetComponent(ItemManager);
if(x.weight + itemObj.itemWeight <= x.maxWeight) {
x.weight += itemObj.itemWeight;
x.invList.Add(itemObj);
Destroy(gameObject);
}
}
I have a lot of functionality added into this inventory, and it works in general, but inventory management is a pain in the rear because my inventory List is of type Item. This means that I cannot access all of the data for each item in my List.
I must first create a variable of the same type ie
var temp : CanOfBeans;
and then assign temp to invList*.*
```
*//Code to use a Can of Beans.
var temp : CanOfBeans = gameObject.GetComponent(ItemManager).invList[target];
transform.parent.gameObject.GetComponent(PlayerAttributes).hunger += temp.recoverHunger;
gameObject.GetComponent(ItemManager).invList.RemoveAt(target);
temp.numUses -= 1;
if(temp.numUses > 0)
gameObject.GetComponent(ItemManager).invList.Add(temp);
itemUseOn = false;
//Instead of assigning it to temp, I would rather be able to access it directly through
//gameObject.GetComponent(ItemManager).invList[target].recoverHunger;*
```
I realize that this is because the items in invList are type Item but I do not know how to resolve this. Item management is going to get more intense going forward and I need to resolve this before it gets too messy.
Thanks.