using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public static Inventory _instance;
private TweenPosition tween;
private int coinCount = 1000;//金币总数
public List<InventoryItemGrid> itemGridList = new List<InventoryItemGrid>();
public UILabel coinNumberLabel;
public GameObject inventoryItem;
void Awake()
{
_instance = this;
tween = this.GetComponent<TweenPosition>();
}
private bool isShow = false;
void Show()
{
isShow = true;
tween.PlayForward();
}
void Hide()
{
isShow = false;
tween.PlayReverse();
}
public void TransformState()
{
if (isShow == false)
{
Show();
}
else
{
Hide();
}
}
public bool GetCoin(int count)
{
if (coinCount > count)
{
coinCount -= count;
coinNumberLabel.text = coinCount.ToString();
return true;
}
return false;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.X))
{
GetId(Random.Range(2001, 2023));
}
}
//拾取到id的物品,并添加到物品栏里面
//处理拾取物品的功能
public void GetId(int id,int count=1)
{
//第一查找在所有的物品中是否存在该物品
//第二如果存在,让num+1
//第三如果不存在,查找空方格,然后把新创建的InventoryItem放到这个空的方格里面
InventoryItemGrid grid = null;
foreach (InventoryItemGrid temp in itemGridList)
{
if (temp.id == id)
{
grid = temp;
break;
}
}
if (grid != null)//存在的情况
{
grid.PlusNumber(count);
}
else//不存在情况
{
foreach (InventoryItemGrid temp in itemGridList)
{
if (temp.id == 0)
{
grid = temp; break;
}
}
//第三如果不存在,查找空方格,然后把新创建的InventoryItem放到这个空的方格里面
if (grid != null)
{
GameObject itemGo = NGUITools.AddChild(grid.gameObject, inventoryItem);
itemGo.transform.localPosition = Vector3.zero;
grid.SetId(id,count);
}
}
}
}
先检查一下,随机生成的id 是否是随机的
if (temp.id == id)
{
grid = temp;
break;
}
看下这个得到的temp.id是否正确
最后检查一下
grid.SetId(id,count);
这里setid的时候,是否能根据id获取到争取的物品