mmorpg/Assets/Script/Inventory/InventoryManager.cs
2024-07-21 21:52:51 +05:30

145 lines
3.5 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
public class InventoryManager : MonoBehaviour
{
public playerNetwork pnet;
public InventorySlot[] inventorySlots;
public InventoryItemsCollection lootsData;
public GameObject ItemInventoryPrefab;
public List<item> startingItems;
public bool resetInventory = false;
private void OnValidate()
{
if (resetInventory)
{
resetInventory= false;
foreach(InventorySlot slot in inventorySlots)
{
slot.Clear();
}
}
}
public item GetItemByType(string type)
{
foreach(item i in lootsData.items)
{
if(i.type == type)
{
return i;
}
}
Debug.Log("Could not find anything for " + type);
return null;
}
void Start(){
foreach(item i in startingItems){
AddInvItem(i);
}
}
public Dictionary<int, string> GetEntries(){
Dictionary<int, string> entries = new Dictionary<int, string>();
for(int i=0; i < inventorySlots.Length; i++){
ItemInventory itemInSlot = inventorySlots[i].GetComponentInChildren<ItemInventory>();
if(itemInSlot!= null && itemInSlot.item != null){
entries.Add(i, itemInSlot.item.type);
}
}
return entries;
}
public void SetInventory(Dictionary<int, string> data)
{
Clear();
foreach(KeyValuePair<int, string> entry in data)
{
SpawnNewItem(GetItemByType(entry.Value), inventorySlots[entry.Key]);
}
}
public bool UseItem(item i)
{
if(pnet.health >= 100)
{
return false;
}
pnet.SetHealth(pnet.health+i.healthIncrease);
pnet.SavePlayerData();
return true;
}
public item selectedItem;
public void SelectItem(item itemI){
selectedItem = itemI;
}
public void DropItem(item i)
{
pnet.DropPickup(i.type);
pnet.SavePlayerData();
}
public void AddInvItem(string type)
{
AddInvItem(GetItemByType(type));
}
public void AddInvItem (item item){
//find an empty slot
for(int i = inventorySlots.Length-1; i >=0 ; i--){
InventorySlot slot = inventorySlots[i];
ItemInventory itemInSlot = slot.GetComponentInChildren<ItemInventory>();
if(itemInSlot == null){
SpawnNewItem(item , slot);
return;
}
//implement check for slot full
}
Debug.Log("Slots are full");
}
public void Clear(){
for(int i=0; i < inventorySlots.Length; i++){
if(inventorySlots[i].transform.childCount > 0){
Destroy(inventorySlots[i].transform.GetChild(0).gameObject);
}
}
}
void SpawnNewItem(item item , InventorySlot slot ){
GameObject newItemAdd = Instantiate(ItemInventoryPrefab , slot.transform);
ItemInventory inventoryItemm = newItemAdd.GetComponent<ItemInventory>();
inventoryItemm.Set(item,this);
pnet.SavePlayerData();
}
}
[System.Serializable]
public class InventoryEntry{
public int slot;
public string item;
}