Hey there, I’m trying to create an inventory for my player. I created this short javascript code and didn’t seem to work. Any ideas? I’ve tried fixing the errors but only leading to more. Please help!
public class Inventory
List items = new List();
InventoryItem selectedItem;
Player owner;
int currentlySelected = 0;
public void Init(Player newPlayer)
{
newPlayer = owner;
}
public bool AddItem(InventoryItem newItem)
{
if(owner.strength >= GetTotalMass() + newItem.mass)
{
items.Add(newItem);
return true;
} else {
return false;
}
}
public void DropItem(InventoryItem newItem)
{
items.Remove(newItem);
}
public float GetTotalMass()
{
float mass = 0;
foreach(InventoryItem it in items)
{
mass += it.mass;
}
return mass;
}
public InventoryItem DrawItemsGrid(int columns)
{
Texture2D[] textures = GetTextures();
currentlySelected = GUILayout.SelectionGrid(currentlySelected, textures, columns);
return items[currentlySelected];
}
public Texture2D[] GetTextures()
{
List textures = new List();
foreach(InventoryItem it in items)
{
textures.Add(it.icon);
}
return textures.ToArray();
}
}
public class Player : MonoBehaviour
{
public float strength;
public Inventory invent;
public Hat myHat;
public Sword mySword;
public Sword myOtherSword;
void Start()
{
invent.Init(this);
invent.Add(myHat);
invent.Add(mySword);
invent.Add(myOtherSword);
}
public void TipHat()
{
//play a hat-tipping animation!
}
public void Attack()
{
// swing a sword
}
void OnGUI()
{
InventoryItem currentItem = invent.DrawItemsGrid(2);
currentItem.DrawGUIInfo();
if(GUILayout.Button("Activate " + currentItem.itemName))
{
currentItem.Activate(this);
}
if(GUILayout.Button("Drop " + currentItem.itemName))
{
invent.DropItem(currentItem);
}
}
}
public abstract class InventoryItem
{
public string itemName;
public string dragInfo;
public float mass;
public Texture2D icon;
public abstract void Activate(Player player);
public void DrawGUIInfo(){ GUILayout.Label(dragInfo); }
}
[System.Serializable]
public class Hat : InventoryItem
{
void Activate(Player player)
{
player.TipHat();
}
}
[System.Serializable]
public class Sword : InventoryItem
{
void Activate(Player player)
{
player.Attack();
}
}
[Edit by Berenger : formatting. Please next time select your code and hit the 101 010 button.]