Inventory
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Text; /// <summary> /// 面板基类 /// </summary> public class Inventory:MonoBehaviour { /// <summary> /// 插槽列表 /// </summary> protected Slot[] slotList; /// <summary> /// 目标透明度 /// </summary> ; /// <summary> /// 动画速度 /// </summary> ; /// <summary> /// CanvasGroup /// </summary> private CanvasGroup canvasGroup; public virtual void Start() { slotList = GetComponentsInChildren<Slot>(); canvasGroup = GetComponent<CanvasGroup>(); } void Update() { if(canvasGroup.alpha != targetAlpha) { canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha,targetAlpha,smoothing * Time.deltaTime); if(Mathf.Abs(canvasGroup.alpha - targetAlpha) < .01f) { canvasGroup.alpha = targetAlpha; } } } /// <summary> /// 根据物品ID存储物品 /// </summary> public bool StoreItem(int id) { Item item = InventoryManager.Instance.GetItemById(id); return StoreItem(item); } /// <summary> /// 存储物品 /// </summary> public bool StoreItem(Item item) { if(item == null) { Debug.LogWarning("要存储的物品的id不存在"); return false; } ) { Slot slot = FindEmptySlot(); if(slot == null) { Debug.LogWarning("没有空的物品槽"); return false; } else { slot.StoreItem(item);//把物品存储到这个空的物品槽里面 } } else { Slot slot = FindSameIdSlot(item); if(slot != null) { slot.StoreItem(item); } else { Slot emptySlot = FindEmptySlot(); if(emptySlot != null) { emptySlot.StoreItem(item); } else { Debug.LogWarning("没有空的物品槽"); return false; } } } return true; } /// <summary> /// 查找空插槽 /// </summary> private Slot FindEmptySlot() { //遍历插槽列表 foreach(Slot slot in slotList) { //没有子物体 ) { //返回这个插槽 return slot; } } return null; } /// <summary> /// 查抄相同ID的插槽 /// </summary> private Slot FindSameIdSlot(Item item) { //遍历插槽列表 foreach(Slot slot in slotList) { //有子物体,ID相同,插槽没满 && slot.GetItemId() == item.ID && slot.IsFilled() == false) { //返回插槽 return slot; } } return null; } /// <summary> /// 显示 /// </summary> public void Show() { canvasGroup.blocksRaycasts = true; targetAlpha = ; } /// <summary> /// 隐藏 /// </summary> public void Hide() { canvasGroup.blocksRaycasts = false; targetAlpha = ; } /// <summary> /// 切换显示/隐藏 /// </summary> public void DisplaySwitch() { ) { Show(); } else { Hide(); } } /// <summary> /// 保存信息 /// </summary> public void SaveInventory() { StringBuilder sb = new StringBuilder(); //遍历插槽 foreach(Slot slot in slotList) { //有子物体 ) { //获取物品UI ItemUI itemUI = slot.transform.GetChild().GetComponent<ItemUI>(); sb.Append(itemUI.Item.ID + "," + itemUI.Amount + "-"); } else { sb.Append("0-"); } } PlayerPrefs.SetString(this.gameObject.name,sb.ToString()); } /// <summary> /// 加载信息 /// </summary> public void LoadInventory() { if(PlayerPrefs.HasKey(this.gameObject.name) == false) return; string str = PlayerPrefs.GetString(this.gameObject.name); string[] itemArray = str.Split('-'); ;i < itemArray.Length - ;i++) { string itemStr = itemArray[i]; ") { print(itemStr); string[] temp = itemStr.Split(','); ]); Item item = InventoryManager.Instance.GetItemById(id); ]); ;j < amount;j++) { slotList[i].StoreItem(item); } } } } }
Inventory
using UnityEngine; using System.Collections; using UnityEngine.UI; /// <summary> /// 角色面板 /// </summary> public class CharacterPanel : Inventory { /// <summary> /// 单例 /// </summary> private static CharacterPanel _instance; /// <summary> /// 单例 /// </summary> public static CharacterPanel Instance { get { if (_instance == null) { _instance = GameObject.Find("CharacterPanel").GetComponent<CharacterPanel>(); } return _instance; } } /// <summary> /// 属性文本 /// </summary> private Text propertyText; /// <summary> /// 玩家 /// </summary> private Player player; public override void Start() { base.Start(); propertyText = transform.Find("PropertyPanel/Text").GetComponent<Text>(); player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); UpdatePropertyText(); Hide(); } /// <summary> /// 穿装备和武器 /// </summary> public void PutOn(Item item) { Item exitItem = null; foreach (Slot slot in slotList) { EquipmentSlot equipmentSlot = (EquipmentSlot)slot; if (equipmentSlot.IsRightItem(item)) { ) { ItemUI currentItemUI= equipmentSlot.transform.GetChild().GetComponent<ItemUI>(); exitItem = currentItemUI.Item; currentItemUI.SetItem(item, ); } else { equipmentSlot.StoreItem(item); } break; } } if(exitItem!=null) KnapsackPanel.Instance.StoreItem(exitItem); UpdatePropertyText(); } public void PutOff(Item item) { KnapsackPanel.Instance.StoreItem(item); UpdatePropertyText(); } private void UpdatePropertyText() { //Debug.Log("UpdatePropertyText"); , intellect = , agility = , stamina = , damage = ; foreach(EquipmentSlot slot in slotList){ ) { Item item = slot.transform.GetChild().GetComponent<ItemUI>().Item; if (item is Equipment) { Equipment e = (Equipment)item; strength += e.Strength; intellect += e.Intellect; agility += e.Agility; stamina += e.Stamina; } else if (item is Weapon) { damage += ((Weapon)item).Damage; } } } strength += player.BasicStrength; intellect += player.BasicIntellect; agility += player.BasicAgility; stamina += player.BasicStamina; damage += player.BasicDamage; string text = string.Format("力量:{0}\n智力:{1}\n敏捷:{2}\n体力:{3}\n攻击力:{4} ", strength, intellect, agility, stamina, damage); propertyText.text = text; } }
CharacterPanel
using UnityEngine; using System.Collections; /// <summary> /// 箱子面板 /// </summary> public class ChestPanel : Inventory { /// <summary> /// 单例 /// </summary> private static ChestPanel _instance; /// <summary> /// 单例 /// </summary> public static ChestPanel Instance { get { if (_instance == null) { _instance = GameObject.Find("ChestPanel").GetComponent<ChestPanel>(); } return _instance; } } }
ChestPanel
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// 锻造面板 /// </summary> public class ForgePanel : Inventory { /// <summary> /// 单例 /// </summary> private static ForgePanel _instance; /// <summary> /// 单例 /// </summary> public static ForgePanel Instance { get { if (_instance == null) { _instance = GameObject.Find("ForgePanel").GetComponent<ForgePanel>(); } return _instance; } } /// <summary> /// /// </summary> private List<Formula> formulaList; public override void Start() { base.Start(); ParseFormulaJson(); } void ParseFormulaJson() { formulaList = new List<Formula>(); TextAsset formulasText = Resources.Load<TextAsset>("Formulas"); string formulasJson = formulasText.text;//配方信息的Json数据 JSONObject jo = new JSONObject(formulasJson); foreach (JSONObject temp in jo.list) { int item1ID = (int)temp["Item1ID"].n; int item1Amount = (int)temp["Item1Amount"].n; int item2ID = (int)temp["Item2ID"].n; int item2Amount = (int)temp["Item2Amount"].n; int resID = (int)temp["ResID"].n; Formula formula = new Formula(item1ID, item1Amount, item2ID, item2Amount, resID); formulaList.Add(formula); } //Debug.Log(formulaList[1].ResID); } public void ForgeItem(){ // 得到当前有哪些材料 // 判断满足哪一个秘籍的要求 List<int> haveMaterialIDList = new List<int>();//存储当前拥有的材料的id foreach (Slot slot in slotList) { ) { ItemUI currentItemUI = slot.transform.GetChild().GetComponent<ItemUI>(); ; i < currentItemUI.Amount; i++) { haveMaterialIDList.Add(currentItemUI.Item.ID);//这个格子里面有多少个物品 就存储多少个id } } } Formula matchedFormula = null; foreach (Formula formula in formulaList) { bool isMatch = formula.Match(haveMaterialIDList); if (isMatch) { matchedFormula = formula; break; } } if (matchedFormula != null) { KnapsackPanel.Instance.StoreItem(matchedFormula.ResID); //去掉消耗的材料 foreach(int id in matchedFormula.NeedIdList){ foreach (Slot slot in slotList) { ) { ItemUI itemUI = slot.transform.GetChild().GetComponent<ItemUI>(); ) { itemUI.ReduceAmount(); ) { DestroyImmediate(itemUI.gameObject); } break; } } } } } } }
ForgePanel
using UnityEngine; using System.Collections; /// <summary> /// 背包 /// </summary> public class KnapsackPanel : Inventory { /// <summary> /// 单例 /// </summary> private static KnapsackPanel _instance; /// <summary> /// 单例 /// </summary> public static KnapsackPanel Instance { get { if (_instance == null) { _instance = GameObject.Find("KnapsackPanel").GetComponent<KnapsackPanel>(); } return _instance; } } }
KnapsackPanel
using UnityEngine; using System.Collections; /// <summary> /// 商店面板 /// </summary> public class VendorPanel : Inventory { /// <summary> /// 单例 /// </summary> private static VendorPanel _instance; /// <summary> /// 单例 /// </summary> public static VendorPanel Instance { get { if (_instance == null) { _instance = GameObject.Find("VendorPanel").GetComponent<VendorPanel>(); } return _instance; } } /// <summary> /// 物品ID列表 /// </summary> public int[] itemIdArray; /// <summary> /// 玩家 /// </summary> private Player player; public override void Start() { base.Start(); InitShop(); player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); Hide(); } private void InitShop() { foreach (int itemId in itemIdArray) { StoreItem(itemId); } } /// <summary> /// 主角购买 /// </summary> /// <param name="item"></param> public void BuyItem(Item item) { bool isSuccess = player.ConsumeCoin(item.BuyPrice); if (isSuccess) { KnapsackPanel.Instance.StoreItem(item); } } /// <summary> /// 主角出售物品 /// </summary> public void SellItem() { ; if (Input.GetKey(KeyCode.LeftControl)) { sellAmount = ; } else { sellAmount = InventoryManager.Instance.PickedItemUI.Amount; } int coinAmount = InventoryManager.Instance.PickedItemUI.Item.SellPrice * sellAmount; player.EarnCoin(coinAmount); InventoryManager.Instance.RemoveItem(sellAmount); } }
VendorPanel
Item
using UnityEngine; using System.Collections; using UnityEngine.UI; /// <summary> /// UI物品 /// </summary> public class ItemUI:MonoBehaviour { /// <summary> /// 关联的物品 /// </summary> public Item Item { get; private set; } /// <summary> /// 关联的数量 /// </summary> public int Amount { get; private set; } /// <summary> /// 物品图片 /// </summary> private Image itemImage; /// <summary> /// 数量文本 /// </summary> private Text amountText; /// <summary> /// 物品图片 /// </summary> private Image ItemImage { get { if(itemImage == null) { itemImage = GetComponent<Image>(); } return itemImage; } } /// <summary> /// 数量文本 /// </summary> private Text AmountText { get { if(amountText == null) { amountText = GetComponentInChildren<Text>(); } return amountText; } } /// <summary> /// 目标缩放 /// </summary> private float targetScale = 1f; /// <summary> /// 动画缩放 /// </summary> private Vector3 animationScale = new Vector3(1.4f,1.4f,1.4f); /// <summary> /// 动画速度 /// </summary> ; void Update() { //当前缩放不等于目标缩放 if(transform.localScale.x != targetScale) { //计算缩放插值 float scale = Mathf.Lerp(transform.localScale.x,targetScale,smoothing * Time.deltaTime); //修改缩放 transform.localScale = new Vector3(scale,scale,scale); //当前缩放和目标缩放的差值小于0.2 if(Mathf.Abs(transform.localScale.x - targetScale) < .02f) { //修改为目标缩放 transform.localScale = new Vector3(targetScale,targetScale,targetScale); } } } /// <summary> /// 设置物品 /// </summary> ) { //修改缩放 transform.localScale = animationScale; //设置物品 this.Item = item; //设置数量 this.Amount = amount; //根据精灵名称加载精灵 ItemImage.sprite = Resources.Load<Sprite>(item.Sprite); //容量大于1 ) //修改数量文本 AmountText.text = Amount.ToString(); //容量不大于1 else //不显示数量文本 AmountText.text = ""; } /// <summary> /// 增加数量 /// </summary> ) { ///修改缩放 transform.localScale = animationScale; //增加数量 this.Amount += amount; //容量大于1 ) //修改数量 AmountText.text = Amount.ToString(); //容量不大于1 else //不显示数量文本 AmountText.text = ""; } /// <summary> /// 减少数量 /// </summary> ) { //修改缩放 transform.localScale = animationScale; //减少数量 this.Amount -= amount; //根据容量显示数量 ) AmountText.text = Amount.ToString(); else AmountText.text = ""; } /// <summary> /// 设置数量 /// </summary> public void SetAmount(int amount) { transform.localScale = animationScale; this.Amount = amount; //根据容量显示数量 ) AmountText.text = Amount.ToString(); else AmountText.text = ""; } /// <summary> /// 交换物品UI /// </summary> public void Exchange(ItemUI itemUI) { Item itemTemp = itemUI.Item; int amountTemp = itemUI.Amount; itemUI.SetItem(this.Item,this.Amount); this.SetItem(itemTemp,amountTemp); } /// <summary> /// 显示 /// </summary> public void Show() { gameObject.SetActive(true); } /// <summary> /// 隐藏 /// </summary> public void Hide() { gameObject.SetActive(false); } /// <summary> /// 设置局部坐标 /// </summary> public void SetLocalPosition(Vector3 position) { transform.localPosition = position; } }
ItemUI
using UnityEngine; using System.Collections; /// <summary> /// 物品基类 /// </summary> public class Item { /// <summary> /// ID /// </summary> public int ID { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 类型 /// </summary> public ItemType Type { get; set; } /// <summary> /// 质量 /// </summary> public ItemQuality Quality { get; set; } /// <summary> /// 描述 /// </summary> public string Description { get; set; } /// <summary> /// 容量 /// </summary> public int Capacity { get; set; } /// <summary> /// 买的价格 /// </summary> public int BuyPrice { get; set; } /// <summary> /// 卖的价格 /// </summary> public int SellPrice { get; set; } /// <summary> /// 图片 /// </summary> public string Sprite { get; set; } public Item() { //默认ID-1 ; } public Item(int id,string name,ItemType type,ItemQuality quality,string des,int capacity,int buyPrice,int sellPrice,string sprite) { this.ID = id; this.Name = name; this.Type = type; this.Quality = quality; this.Description = des; this.Capacity = capacity; this.BuyPrice = buyPrice; this.SellPrice = sellPrice; this.Sprite = sprite; } /// <summary> /// 物品类型 /// </summary> public enum ItemType { /// <summary> /// 消耗品 /// </summary> Consumable, /// <summary> /// 装备 /// </summary> Equipment, /// <summary> /// 武器 /// </summary> Weapon, /// <summary> /// 材料 /// </summary> Material } /// <summary> /// 品质 /// </summary> public enum ItemQuality { /// <summary> /// 普通 /// </summary> Common, /// <summary> /// 罕见 /// </summary> Uncommon, /// <summary> /// 稀有 /// </summary> Rare, /// <summary> /// 史诗 /// </summary> Epic, /// <summary> /// 传奇 /// </summary> Legendary, /// <summary> /// 远古 /// </summary> Artifact } /// <summary> /// 获取提示文本 /// </summary> /// <returns></returns> public virtual string GetToolTipText() { string color = ""; switch(Quality) { case ItemQuality.Common: color = "white"; break; case ItemQuality.Uncommon: color = "lime"; break; case ItemQuality.Rare: color = "navy"; break; case ItemQuality.Epic: color = "magenta"; break; case ItemQuality.Legendary: color = "orange"; break; case ItemQuality.Artifact: color = "red"; break; } string text = string.Format("<color={4}>{0}</color>\n<size=10><color=green>购买价格:{1} 出售价格:{2}</color></size>\n<color=yellow><size=10>{3}</size></color>",Name,BuyPrice,SellPrice,Description,color); return text; } }
Item
using UnityEngine; using System.Collections; /// <summary> /// 消耗品类 /// </summary> public class Consumable:Item { /// <summary> /// 增加的血量 /// </summary> public int HP { get; set; } /// <summary> /// 增加的蓝量 /// </summary> public int MP { get; set; } public Consumable(int id,string name,ItemType type,ItemQuality quality,string des,int capacity,int buyPrice,int sellPrice,string sprite,int hp,int mp) : base(id,name,type,quality,des,capacity,buyPrice,sellPrice,sprite) { this.HP = hp; this.MP = mp; } public override string GetToolTipText() { string text = base.GetToolTipText(); string newText = string.Format("{0}\n\n<color=blue>加血:{1}\n加蓝:{2}</color>",text,HP,MP); return newText; } public override string ToString() { string s = ""; s += ID.ToString(); s += Type; s += Quality; s += Description; s += Capacity; s += BuyPrice; s += SellPrice; s += Sprite; s += HP; s += MP; return s; } }
Consumable
using UnityEngine; using System.Collections; /// <summary> /// 装备 /// </summary> public class Equipment:Item { /// <summary> /// 力量 /// </summary> public int Strength { get; set; } /// <summary> /// 智力 /// </summary> public int Intellect { get; set; } /// <summary> /// 敏捷 /// </summary> public int Agility { get; set; } /// <summary> /// 体力 /// </summary> public int Stamina { get; set; } /// <summary> /// 装备类型 /// </summary> public EquipmentType EquipType { get; set; } public Equipment(int id,string name,ItemType type,ItemQuality quality,string des,int capacity,int buyPrice,int sellPrice,string sprite, int strength,int intellect,int agility,int stamina,EquipmentType equipType) : base(id,name,type,quality,des,capacity,buyPrice,sellPrice,sprite) { this.Strength = strength; this.Intellect = intellect; this.Agility = agility; this.Stamina = stamina; this.EquipType = equipType; } /// <summary> /// 装备类型 /// </summary> public enum EquipmentType { /// <summary> /// 默认 /// </summary> None, /// <summary> /// 头 /// </summary> Head, /// <summary> /// 脖子 /// </summary> Neck, /// <summary> /// 胸 /// </summary> Chest, /// <summary> /// 戒指 /// </summary> Ring, /// <summary> /// 腿 /// </summary> Leg, /// <summary> /// 护腕 /// </summary> Bracer, /// <summary> /// 鞋子 /// </summary> Boots, /// <summary> /// 肩膀 /// </summary> Shoulder, /// <summary> /// 腰带 /// </summary> Belt, /// <summary> /// 副手 /// </summary> OffHand } public override string GetToolTipText() { string text = base.GetToolTipText(); string equipTypeText = ""; switch(EquipType) { case EquipmentType.Head: equipTypeText = "头部"; break; case EquipmentType.Neck: equipTypeText = "脖子"; break; case EquipmentType.Chest: equipTypeText = "胸部"; break; case EquipmentType.Ring: equipTypeText = "戒指"; break; case EquipmentType.Leg: equipTypeText = "腿部"; break; case EquipmentType.Bracer: equipTypeText = "护腕"; break; case EquipmentType.Boots: equipTypeText = "靴子"; break; case EquipmentType.Shoulder: equipTypeText = "护肩"; break; case EquipmentType.Belt: equipTypeText = "腰带"; break; case EquipmentType.OffHand: equipTypeText = "副手"; break; } string newText = string.Format("{0}\n\n<color=blue>装备类型:{1}\n力量:{2}\n智力:{3}\n敏捷:{4}\n体力:{5}</color>",text,equipTypeText,Strength,Intellect,Agility,Stamina); return newText; } }
Equipment
using UnityEngine; using System.Collections; /// <summary> /// 材料类 /// </summary> public class Material:Item { public Material(int id,string name,ItemType type,ItemQuality quality,string des,int capacity,int buyPrice,int sellPrice,string sprite) : base(id,name,type,quality,des,capacity,buyPrice,sellPrice,sprite) { } }
Material
using UnityEngine; using System.Collections; /// <summary> /// 武器 /// </summary> public class Weapon:Item { /// <summary> /// 伤害 /// </summary> public int Damage { get; set; } /// <summary> /// 武器类型 /// </summary> public WeaponType WpType { get; set; } public Weapon(int id,string name,ItemType type,ItemQuality quality,string des,int capacity,int buyPrice,int sellPrice,string sprite, int damage,WeaponType wpType) : base(id,name,type,quality,des,capacity,buyPrice,sellPrice,sprite) { this.Damage = damage; this.WpType = wpType; } /// <summary> /// 武器类型 /// </summary> public enum WeaponType { /// <summary> /// 默认 /// </summary> None, /// <summary> /// 副手 /// </summary> OffHand, /// <summary> /// 主手 /// </summary> MainHand } /// <summary> /// 获取提示信息 /// </summary> public override string GetToolTipText() { string text = base.GetToolTipText(); string wpTypeText = ""; switch(WpType) { case WeaponType.OffHand: wpTypeText = "副手"; break; case WeaponType.MainHand: wpTypeText = "主手"; break; } string newText = string.Format("{0}\n\n<color=blue>武器类型:{1}\n攻击力:{2}</color>",text,wpTypeText,Damage); return newText; } }
Weapon
Slot
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; /// <summary> /// 物品槽 /// </summary> public class Slot:MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler { /// <summary> /// 物品预设 /// </summary> public GameObject itemPrefab; /// <summary> /// 存储物品 /// </summary> public void StoreItem(Item item) { //没有子物体 ) { //实例化预设 GameObject itemGameObject = Instantiate(itemPrefab) as GameObject; //设置父物体 itemGameObject.transform.SetParent(this.transform); //设置缩放 itemGameObject.transform.localScale = Vector3.one; //设置位置 itemGameObject.transform.localPosition = Vector3.zero; itemGameObject.GetComponent<ItemUI>().SetItem(item); //有子物体 } else { //物品数量加1 transform.GetChild().GetComponent<ItemUI>().AddAmount(); } } /// <summary> /// 得到当前物品槽存储的物品类型 /// </summary> public Item.ItemType GetItemType() { ).GetComponent<ItemUI>().Item.Type; } /// <summary> /// 得到物品的id /// </summary> /// <returns></returns> public int GetItemId() { ).GetComponent<ItemUI>().Item.ID; } /// <summary> /// 是否满了 /// </summary> /// <returns></returns> public bool IsFilled() { ItemUI itemUI = transform.GetChild().GetComponent<ItemUI>(); //当前的数量是否大于等于容量 return itemUI.Amount >= itemUI.Item.Capacity; } /// <summary> /// 鼠标进入 /// </summary> public void OnPointerEnter(PointerEventData eventData) { //子物体数量大于0 ) { //获取物品的提示文本 ).GetComponent<ItemUI>().Item.GetToolTipText(); //显示提示文本 InventoryManager.Instance.ShowToolTip(toolTipText); } } /// <summary> /// 鼠标移除 /// </summary> public void OnPointerExit(PointerEventData eventData) { //子物体数量大于0 ) //隐藏提示文本 InventoryManager.Instance.HideToolTip(); } /// <summary> /// 鼠标按下 /// </summary> public virtual void OnPointerDown(PointerEventData eventData) { //右键点击 if(eventData.button == PointerEventData.InputButton.Right) { //没有选取的物品且子物体数量大于0 ) { //获取物品UI ItemUI currentItemUI = transform.GetChild().GetComponent<ItemUI>(); //如果物品是装备或武器 if(currentItemUI.Item is Equipment || currentItemUI.Item is Weapon) { //数量减1 currentItemUI.ReduceAmount(); //获取物品 Item currentItem = currentItemUI.Item; //物品UI数量小于等于0 ) { //删除物品UI DestroyImmediate(currentItemUI.gameObject); //隐藏提示文本 InventoryManager.Instance.HideToolTip(); } //穿装备和武器 CharacterPanel.Instance.PutOn(currentItem); } } } //不是左键,返回 if(eventData.button != PointerEventData.InputButton.Left) return; //子物体数量大于0 ) { //获取当前ItemUI ItemUI currentItemUI = transform.GetChild().GetComponent<ItemUI>(); //鼠标上没有物品 if(InventoryManager.Instance.IsPickedItem == false) { //同时按下左Control if(Input.GetKey(KeyCode.LeftControl)) { //计算拾取物品的数量 ) / ; //鼠标拾取物品 InventoryManager.Instance.PickupItem(currentItemUI.Item,amountPicked); //计算剩余数量 int amountRemained = currentItemUI.Amount - amountPicked; //剩余数量小于等于0 ) { //销毁当前物品UI Destroy(currentItemUI.gameObject);//销毁当前物品 //剩余数量大于0 } else { //修改剩余数量 currentItemUI.SetAmount(amountRemained); } //没有按下左Control } else { //拾取物品 InventoryManager.Instance.PickupItem(currentItemUI.Item,currentItemUI.Amount); //销毁当前物品 Destroy(currentItemUI.gameObject); } //鼠标上有物品 } else { //拾取物品ID等于当前物品ID if(currentItemUI.Item.ID == InventoryManager.Instance.PickedItemUI.Item.ID) { //同时按下左Control if(Input.GetKey(KeyCode.LeftControl)) { //当前物品UI的容量大于当前物品UI的数量 if(currentItemUI.Item.Capacity > currentItemUI.Amount) { //当前物品UI增加数量 currentItemUI.AddAmount(); //减少鼠标物品UI的数量 InventoryManager.Instance.RemoveItem(); //容量小于数量,不处理 } else { return; } //没有按下左Control } else { //当前物品UI的容量大于当前物品UI的数量 if(currentItemUI.Item.Capacity > currentItemUI.Amount) { //获取当前物品UI的剩余数量 int amountRemain = currentItemUI.Item.Capacity - currentItemUI.Amount;//当前物品槽剩余的空间 //当前物品UI的剩余数量大于等于鼠标物品UI的数量 if(amountRemain >= InventoryManager.Instance.PickedItemUI.Amount) { //修改当前物品UI数量 currentItemUI.SetAmount(currentItemUI.Amount + InventoryManager.Instance.PickedItemUI.Amount); //鼠标物品UI移除相应数量 InventoryManager.Instance.RemoveItem(InventoryManager.Instance.PickedItemUI.Amount); //当前物品UI的容量小于等于当前物品UI的数量 } else { //修改当前物品UI数量 currentItemUI.SetAmount(currentItemUI.Amount + amountRemain); //鼠标物品UI移除相应数量 InventoryManager.Instance.RemoveItem(amountRemain); } //当前物品UI的容量小于等于当前物品UI的数量,不处理 } else { return; } } //拾取物品ID不等于当前物品ID } else { //获取当前物品 Item item = currentItemUI.Item; //获取当前物品数量 int amount = currentItemUI.Amount; //设置当前物品为鼠标拾取物品 currentItemUI.SetItem(InventoryManager.Instance.PickedItemUI.Item,InventoryManager.Instance.PickedItemUI.Amount); //设置鼠标拾取物品为当前物品 InventoryManager.Instance.PickedItemUI.SetItem(item,amount); } } //子物体数量小于等于0 } else { //鼠标上有拾取物品 if(InventoryManager.Instance.IsPickedItem == true) { //同时按下左Control if(Input.GetKey(KeyCode.LeftControl)) { //存储物品 this.StoreItem(InventoryManager.Instance.PickedItemUI.Item); //鼠标拾取物体数量减1 InventoryManager.Instance.RemoveItem(); //没有按下左Control } else { //循环添加物品 ;i < InventoryManager.Instance.PickedItemUI.Amount;i++) { this.StoreItem(InventoryManager.Instance.PickedItemUI.Item); } //移除鼠标拾取物品 InventoryManager.Instance.RemoveItem(InventoryManager.Instance.PickedItemUI.Amount); } } else { return; } } } }
Slot
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; /// <summary> /// 装备槽 /// </summary> public class EquipmentSlot : Slot { /// <summary> /// 装备类型 /// </summary> public Equipment.EquipmentType equipType; /// <summary> /// 武器类型 /// </summary> public Weapon.WeaponType wpType; /// <summary> /// 重写鼠标按下 /// </summary> /// <param name="eventData"></param> public override void OnPointerDown(UnityEngine.EventSystems.PointerEventData eventData) { //右键按下 if (eventData.button == PointerEventData.InputButton.Right) { //鼠标上没有拾取物,有子物体 ) { ItemUI currentItemUI = transform.GetChild().GetComponent<ItemUI>(); Item itemTemp = currentItemUI.Item; //删除当前物品UI DestroyImmediate(currentItemUI.gameObject); //脱掉放到背包里面 transform.parent.SendMessage("PutOff", itemTemp); //隐藏提示 InventoryManager.Instance.HideToolTip(); } } //不是左键按下 返回 if (eventData.button != PointerEventData.InputButton.Left) return; // 手上有 东西 //当前装备槽 有装备 //无装备 // 手上没 东西 //当前装备槽 有装备 //无装备 不做处理 bool isUpdateProperty = false; if (InventoryManager.Instance.IsPickedItem == true) { //手上有东西的情况 ItemUI pickedItem = InventoryManager.Instance.PickedItemUI; ) { ItemUI currentItemUI = transform.GetChild().GetComponent<ItemUI>();//当前装备槽里面的物品 if( IsRightItem(pickedItem.Item) ){ InventoryManager.Instance.PickedItemUI.Exchange(currentItemUI); isUpdateProperty = true; } } else { if (IsRightItem(pickedItem.Item)) { this.StoreItem(InventoryManager.Instance.PickedItemUI.Item); InventoryManager.Instance.RemoveItem(); isUpdateProperty = true; } } } else { //手上没东西的情况 ) { ItemUI currentItemUI = transform.GetChild().GetComponent<ItemUI>(); InventoryManager.Instance.PickupItem(currentItemUI.Item, currentItemUI.Amount); Destroy(currentItemUI.gameObject); isUpdateProperty = true; } } if (isUpdateProperty) { transform.parent.SendMessage("UpdatePropertyText"); } } //判断item是否适合放在这个位置 public bool IsRightItem(Item item) { if ((item is Equipment && ((Equipment)(item)).EquipType == this.equipType) || (item is Weapon && ((Weapon)(item)).WpType == this.wpType)) { return true; } return false; } }
EquipmentSlot
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; /// <summary> /// 商店插槽 /// </summary> public class VendorSlot:Slot { /// <summary> /// 重写鼠标按下 /// </summary> public override void OnPointerDown(UnityEngine.EventSystems.PointerEventData eventData) { //按下鼠标右键且鼠标上没有拾取物 if(eventData.button == PointerEventData.InputButton.Right && InventoryManager.Instance.IsPickedItem == false) { //子物体数量大于0 ) { //获取当前物品 Item currentItem = transform.GetChild().GetComponent<ItemUI>().Item; // transform.parent.parent.SendMessage("BuyItem",currentItem); } //按下鼠标左键且鼠标上有拾取物 } else if(eventData.button == PointerEventData.InputButton.Left && InventoryManager.Instance.IsPickedItem == true) { transform.parent.parent.SendMessage("SellItem"); } } }
VendorSlot
Other
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// 配方 /// </summary> public class Formula { /// <summary> /// 物品1ID /// </summary> public int Item1ID { get;private set; } /// <summary> /// 物品1数量 /// </summary> public int Item1Amount { get;private set; } /// <summary> /// 物品2ID /// </summary> public int Item2ID { get;private set; } /// <summary> /// 物品2数量 /// </summary> public int Item2Amount { get;private set; } /// <summary> /// 锻造结果的物品ID /// </summary> public int ResID { get;private set; } /// <summary> /// 所需物品ID列表 /// </summary> private List<int> needIdList = new List<int>(); /// <summary> /// 所需物品ID列表 /// </summary> public List<int> NeedIdList { get { return needIdList; } } public Formula(int item1ID, int item1Amount, int item2ID, int item2Amount, int resID) { this.Item1ID = item1ID; this.Item1Amount = item1Amount; this.Item2ID = item2ID; this.Item2Amount = item2Amount; this.ResID = resID; ; i < Item1Amount; i++) { needIdList.Add(Item1ID); } ; i < Item2Amount; i++) { needIdList.Add(Item2ID); } } /// <summary> /// 提供的物品ID是否匹配所需物品ID /// </summary> public bool Match(List<int> idList ) { List<int> tempIDList = new List<int>(idList); foreach(int id in needIdList){ bool isSuccess = tempIDList.Remove(id); if (isSuccess == false) { return false; } } return true; } }
Formula
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; /// <summary> /// 管理 /// </summary> public class InventoryManager:MonoBehaviour { /// <summary> /// 单例 /// </summary> private static InventoryManager _instance; /// <summary> /// 单例 /// </summary> public static InventoryManager Instance { get { if(_instance == null) { _instance = GameObject.Find("InventoryManager").GetComponent<InventoryManager>(); } return _instance; } } /// <summary> /// 物品列表 /// </summary> private List<Item> itemList; /// <summary> /// 提示 /// </summary> private ToolTip toolTip; /// <summary> /// 提示是否显示 /// </summary> private bool isToolTipShow = false; /// <summary> /// 提示位置 /// </summary> ,-); /// <summary> /// Canvas /// </summary> private Canvas canvas; /// <summary> /// 鼠标上是否有物品UI /// </summary> private bool isPickedItem = false; /// <summary> /// 鼠标上是否有物品UI /// </summary> public bool IsPickedItem { get { return isPickedItem; } } /// <summary> /// 鼠标上的物品UI /// </summary> private ItemUI pickedItemUI; /// <summary> /// 鼠标上的物品UI /// </summary> public ItemUI PickedItemUI { get { return pickedItemUI; } } void Awake() { ParseItemJson(); } void Start() { toolTip = GameObject.FindObjectOfType<ToolTip>(); canvas = GameObject.Find("Canvas").GetComponent<Canvas>(); pickedItemUI = GameObject.Find("PickedItem").GetComponent<ItemUI>(); pickedItemUI.Hide(); } void Update() { //鼠标上有拾取物品UI if(isPickedItem) { //让物品UI跟随鼠标位置 Vector2 position; RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,Input.mousePosition,null,out position); pickedItemUI.SetLocalPosition(position); //显示提示 } else if(isToolTipShow) { //提示跟随鼠标位置 Vector2 position; RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,Input.mousePosition,null,out position); toolTip.SetLocalPotion(position + toolTipPosionOffset); } //丢弃物品 ) && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(-) == false) { isPickedItem = false; PickedItemUI.Hide(); } } /// <summary> /// 解析物品信息 /// </summary> void ParseItemJson() { itemList = new List<Item>(); //加载文本 TextAsset itemText = Resources.Load<TextAsset>("Items"); string itemsJson = itemText.text; //用文本信息创建JSONObject JSONObject j = new JSONObject(itemsJson); //遍历json foreach(JSONObject temp in j.list) { //获取类型字符串 string typeStr = temp["type"].str; //将字符串转换为枚举 Item.ItemType type = (Item.ItemType)System.Enum.Parse(typeof(Item.ItemType),typeStr); //转换共有属性 int id = (int)(temp["id"].n); string name = temp["name"].str; Item.ItemQuality quality = (Item.ItemQuality)System.Enum.Parse(typeof(Item.ItemQuality),temp["quality"].str); string description = temp["description"].str; int capacity = (int)(temp["capacity"].n); int buyPrice = (int)(temp["buyPrice"].n); int sellPrice = (int)(temp["sellPrice"].n); string sprite = temp["sprite"].str; Item item = null; switch(type) { //消耗品 case Item.ItemType.Consumable: int hp = (int)(temp["hp"].n); int mp = (int)(temp["mp"].n); item = new Consumable(id,name,type,quality,description,capacity,buyPrice,sellPrice,sprite,hp,mp); break; //装备 case Item.ItemType.Equipment: int strength = (int)temp["strength"].n; int intellect = (int)temp["intellect"].n; int agility = (int)temp["agility"].n; int stamina = (int)temp["stamina"].n; Equipment.EquipmentType equipType = (Equipment.EquipmentType)System.Enum.Parse(typeof(Equipment.EquipmentType),temp["equipType"].str); item = new Equipment(id,name,type,quality,description,capacity,buyPrice,sellPrice,sprite,strength,intellect,agility,stamina,equipType); break; //武器 case Item.ItemType.Weapon: int damage = (int)temp["damage"].n; Weapon.WeaponType wpType = (Weapon.WeaponType)System.Enum.Parse(typeof(Weapon.WeaponType),temp["weaponType"].str); item = new Weapon(id,name,type,quality,description,capacity,buyPrice,sellPrice,sprite,damage,wpType); break; //材料 case Item.ItemType.Material: item = new Material(id,name,type,quality,description,capacity,buyPrice,sellPrice,sprite); break; } itemList.Add(item); //Debug.Log(item); } } /// <summary> /// 通过ID获取物品 /// </summary> public Item GetItemById(int id) { foreach(Item item in itemList) { if(item.ID == id) { return item; } } return null; } /// <summary> /// 显示提示 /// </summary> public void ShowToolTip(string content) { if(this.isPickedItem) return; isToolTipShow = true; toolTip.Show(content); } /// <summary> /// 隐藏提示 /// </summary> public void HideToolTip() { isToolTipShow = false; toolTip.Hide(); } /// <summary> /// 鼠标拾取物品 /// </summary> public void PickupItem(Item item,int amount) { //设置物品和数量 PickedItemUI.SetItem(item,amount); //修改标志位 isPickedItem = true; //显示拾取物品 PickedItemUI.Show(); //隐藏提示文本 this.toolTip.Hide(); //让物品UI跟随鼠标位置 Vector2 position; RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,Input.mousePosition,null,out position); pickedItemUI.SetLocalPosition(position); } /// <summary> /// 从手上拿掉一个物品放在物品槽里面 /// </summary> ) { //减少数量 PickedItemUI.ReduceAmount(amount); //数量小于等于0 ) { //修改标志位 isPickedItem = false; //隐藏鼠标拾取物品UI PickedItemUI.Hide(); } } /// <summary> /// 保存所有信息 /// </summary> public void SaveInventory() { KnapsackPanel.Instance.SaveInventory(); ChestPanel.Instance.SaveInventory(); CharacterPanel.Instance.SaveInventory(); ForgePanel.Instance.SaveInventory(); PlayerPrefs.SetInt("CoinAmount",GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().CoinAmount); } /// <summary> /// 加载所有信息 /// </summary> public void LoadInventory() { KnapsackPanel.Instance.LoadInventory(); ChestPanel.Instance.LoadInventory(); CharacterPanel.Instance.LoadInventory(); ForgePanel.Instance.LoadInventory(); if(PlayerPrefs.HasKey("CoinAmount")) { GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().CoinAmount = PlayerPrefs.GetInt("CoinAmount"); } } }
InventoryManager
using UnityEngine; using System.Collections; using UnityEngine.UI; /// <summary> /// 玩家 /// </summary> public class Player : MonoBehaviour { /// <summary> /// 基础力量 /// </summary> ; /// <summary> /// 基础智力 /// </summary> ; /// <summary> /// 基础敏捷 /// </summary> ; /// <summary> /// 基础体力 /// </summary> ; /// <summary> /// 基础伤害 /// </summary> ; /// <summary> /// 基础力量 /// </summary> public int BasicStrength { get { return basicStrength; } } /// <summary> /// 基础智力 /// </summary> public int BasicIntellect { get { return basicIntellect; } } /// <summary> /// 基础敏捷 /// </summary> public int BasicAgility { get { return basicAgility; } } /// <summary> /// 基础体力 /// </summary> public int BasicStamina { get { return basicStamina; } } /// <summary> /// 基础伤害 /// </summary> public int BasicDamage { get { return basicDamage; } } /// <summary> /// 金币数量 /// </summary> ; /// <summary> /// 金币数量文本 /// </summary> private Text coinText; /// <summary> /// 金币数量 /// </summary> public int CoinAmount { get { return coinAmount; } set { coinAmount = value; //同时更新文本 coinText.text = coinAmount.ToString(); } } void Start() { //查找金币文本 coinText = GameObject.Find("Coin").GetComponentInChildren<Text>(); //更新金币文本 coinText.text = coinAmount.ToString(); } void Update () { //G 随机得到一个物品放到背包里面 if (Input.GetKeyDown(KeyCode.G)) { , ); KnapsackPanel.Instance.StoreItem(id); } //T 控制背包的显示和隐藏 if (Input.GetKeyDown(KeyCode.T)) { KnapsackPanel.Instance.DisplaySwitch(); } //Y 控制箱子的显示和隐藏 if (Input.GetKeyDown(KeyCode.Y)) { ChestPanel.Instance.DisplaySwitch(); } //U 控制角色面板的 显示和隐藏 if (Input.GetKeyDown(KeyCode.U)) { CharacterPanel.Instance.DisplaySwitch(); } //I 控制商店显示和隐藏 if (Input.GetKeyDown(KeyCode.I)) { VendorPanel.Instance.DisplaySwitch(); } //O 控制锻造界面显示和隐藏 if (Input.GetKeyDown(KeyCode.O)) { ForgePanel.Instance.DisplaySwitch(); } } /// <summary> /// 花费金币 /// </summary> public bool ConsumeCoin(int amount) { if (coinAmount >= amount) { coinAmount -= amount; coinText.text = coinAmount.ToString(); return true; } return false; } /// <summary> /// 赚取金币 /// </summary> public void EarnCoin(int amount) { this.coinAmount += amount; coinText.text = coinAmount.ToString(); } }
Player
using UnityEngine; using System.Collections; using UnityEngine.UI; /// <summary> /// 提示 /// </summary> public class ToolTip : MonoBehaviour { /// <summary> /// 提示文本 /// </summary> private Text toolTipText; /// <summary> /// 内容文本 /// </summary> private Text contentText; /// <summary> /// CanvasGroup /// </summary> private CanvasGroup canvasGroup; /// <summary> /// 目标透明度 /// </summary> ; /// <summary> /// 动画速度 /// </summary> ; void Start() { toolTipText = GetComponent<Text>(); contentText = transform.Find("Content").GetComponent<Text>(); canvasGroup = GetComponent<CanvasGroup>(); } void Update() { //缩放动画 if (canvasGroup.alpha != targetAlpha) { canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, targetAlpha,smoothing*Time.deltaTime); if (Mathf.Abs(canvasGroup.alpha - targetAlpha) < 0.01f) { canvasGroup.alpha = targetAlpha; } } } /// <summary> /// 显示 /// </summary> public void Show(string text) { toolTipText.text = text; contentText.text = text; targetAlpha = ; } /// <summary> /// 隐藏 /// </summary> public void Hide() { targetAlpha = ; } /// <summary> /// 设置局部坐标 /// </summary> public void SetLocalPotion(Vector3 position) { transform.localPosition = position; } }
ToolTip
资源
[ { , "name": "血瓶", "type": "Consumable", "quality": "Common", "description": "这个是用来加血的", , , , , , "sprite": "Sprites/Items/hp" }, { , "name": "蓝瓶", "type": "Consumable", "quality": "Common", "description": "这个是用来加蓝的", , , , , , "sprite": "Sprites/Items/mp" }, { , "name": "胸甲", "type": "Equipment", "quality": "Rare", "description": "这个胸甲很牛B", , , , "sprite": "Sprites/Items/armor", , , , , "equipType": "Chest" }, { , "name": "皮腰带", "type": "Equipment", "quality": "Epic", "description": "这个腰带可以加速", , , , "sprite": "Sprites/Items/belts", , , , , "equipType": "Belt" }, { , "name": "靴子", "type": "Equipment", "quality": "Legendary", "description": "这个靴子可以加速", , , , "sprite": "Sprites/Items/boots", , , , , "equipType": "Boots" }, { , "name": "护腕", "type": "Equipment", "quality": "Rare", "description": "这个护腕可以增加防御", , , , "sprite": "Sprites/Items/bracers", , , , , "equipType": "Bracer" }, { , "name": "神启手套", "type": "Equipment", "quality": "Common", "description": "很厉害的手套", , , , "sprite": "Sprites/Items/gloves", , , , , "equipType": "OffHand" }, { , "name": "头盔", "type": "Equipment", "quality": "Artifact", "description": "很厉害的头盔", , , , "sprite": "Sprites/Items/helmets", , , , , "equipType": "Head" }, { , "name": "项链", "type": "Equipment", "quality": "Rare", "description": "很厉害的项链", , , , "sprite": "Sprites/Items/necklace", , , , , "equipType": "Neck" }, { , "name": "戒指", "type": "Equipment", "quality": "Common", "description": "很厉害的戒指", , , , "sprite": "Sprites/Items/rings", , , , , "equipType": "Ring" }, { , "name": "裤子", "type": "Equipment", "quality": "Uncommon", "description": "很厉害的裤子", , , , "sprite": "Sprites/Items/pants", , , , , "equipType": "Leg" }, { , "name": "护肩", "type": "Equipment", "quality": "Legendary", "description": "很厉害的护肩", , , , "sprite": "Sprites/Items/shoulders", , , , , "equipType": "Shoulder" }, { , "name": "开天斧", "type": "Weapon", "quality": "Rare", "description": "渔翁移山用的斧子", , , , "sprite": "Sprites/Items/axe", , "weaponType": "MainHand" }, { , "name": "阴阳剑", "type": "Weapon", "quality": "Rare", "description": "非常厉害的剑", , , , "sprite": "Sprites/Items/sword", , "weaponType": "OffHand" }, { , "name": "开天斧的锻造秘籍", "type": "Material", "quality": "Artifact", "description": "用来锻造开天斧的秘籍", , , , "sprite": "Sprites/Items/book" }, { , "name": "头盔的锻造秘籍", "type": "Material", "quality": "Common", "description": "用来锻造头盔的秘籍", , , , "sprite": "Sprites/Items/scroll" }, { , "name": "铁块", "type": "Material", "quality": "Common", "description": "用来锻造其他东西的必备材料", , , , "sprite": "Sprites/Items/ingots" } ]
Items.Json
[ { , , , , }, { , , , , } ]
Formulas.Json
项目:https://pan.baidu.com/s/1gf86aY3