This commit is contained in:
Nim XD
2024-08-27 21:01:33 +05:30
parent 99eaf514fd
commit 121a1b7c73
31803 changed files with 623461 additions and 623399 deletions

View File

@@ -1,8 +1,8 @@
fileFormatVersion: 2
guid: cf0f35c6304efdc4bb9a8c8ec5752387
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: cf0f35c6304efdc4bb9a8c8ec5752387
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,72 +1,72 @@
using System;
using Assets.HeroEditor4D.Common.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Newtonsoft.Json;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
/// <summary>
/// Represents item object for storing with game profile (please note, that item params are stored separately in params database).
/// </summary>
[Serializable]
public class Item
{
public string Id; // Id is not unique. Use Hash to compare items!
public Modifier Modifier;
#if TAP_HEROES
public ProtectedInt Count;
#else
public int Count;
#endif
public Item()
{
}
public Item(string id, int count = 1)
{
Id = id;
Count = count;
}
public Item(string id, Modifier modifier, int count = 1)
{
Id = id;
Count = count;
Modifier = modifier;
}
public Item Clone()
{
return new Item(Id, Modifier, Count);
}
[JsonIgnore] public ItemParams Params => ItemCollection.Active.GetItemParams(this);
[JsonIgnore] public ItemSprite Sprite => ItemCollection.Active.GetItemSprite(this);
[JsonIgnore] public ItemIcon Icon => ItemCollection.Active.GetItemIcon(this);
[JsonIgnore] public int Hash => $"{Id}.{Modifier?.Id}.{Modifier?.Level}".GetHashCode();
[JsonIgnore] public bool IsModified => Modifier != null && Modifier.Id != ItemModifier.None;
[JsonIgnore] public bool IsEquipment => Params.Type == ItemType.Helmet || Params.Type == ItemType.Armor || Params.Type == ItemType.Vest || Params.Type == ItemType.Bracers || Params.Type == ItemType.Leggings || Params.Type == ItemType.Weapon || Params.Type == ItemType.Shield;
[JsonIgnore] public bool IsArmor => Params.Type == ItemType.Helmet || Params.Type == ItemType.Armor || Params.Type == ItemType.Vest || Params.Type == ItemType.Bracers || Params.Type == ItemType.Leggings;
[JsonIgnore] public bool IsWeapon => Params.Type == ItemType.Weapon;
[JsonIgnore] public bool IsShield => Params.Type == ItemType.Shield;
[JsonIgnore] public bool IsDagger => Params.Class == ItemClass.Dagger;
[JsonIgnore] public bool IsSword => Params.Class == ItemClass.Sword;
[JsonIgnore] public bool IsAxe => Params.Class == ItemClass.Axe;
[JsonIgnore] public bool IsPickaxe => Params.Class == ItemClass.Pickaxe;
[JsonIgnore] public bool IsWand => Params.Class == ItemClass.Wand;
[JsonIgnore] public bool IsBlunt => Params.Class == ItemClass.Blunt;
[JsonIgnore] public bool IsLance => Params.Class == ItemClass.Lance;
[JsonIgnore] public bool IsMelee => Params.Type == ItemType.Weapon && Params.Class != ItemClass.Bow && Params.Class != ItemClass.Firearm;
[JsonIgnore] public bool IsBow => Params.Class == ItemClass.Bow;
[JsonIgnore] public bool IsFirearm => Params.Class == ItemClass.Firearm;
[JsonIgnore] public bool IsOneHanded => !IsTwoHanded;
[JsonIgnore] public bool IsTwoHanded => Params.Class == ItemClass.Bow || Params.Tags.Contains(ItemTag.TwoHanded);
}
using System;
using Assets.HeroEditor4D.Common.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Newtonsoft.Json;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
/// <summary>
/// Represents item object for storing with game profile (please note, that item params are stored separately in params database).
/// </summary>
[Serializable]
public class Item
{
public string Id; // Id is not unique. Use Hash to compare items!
public Modifier Modifier;
#if TAP_HEROES
public ProtectedInt Count;
#else
public int Count;
#endif
public Item()
{
}
public Item(string id, int count = 1)
{
Id = id;
Count = count;
}
public Item(string id, Modifier modifier, int count = 1)
{
Id = id;
Count = count;
Modifier = modifier;
}
public Item Clone()
{
return new Item(Id, Modifier, Count);
}
[JsonIgnore] public ItemParams Params => ItemCollection.Active.GetItemParams(this);
[JsonIgnore] public ItemSprite Sprite => ItemCollection.Active.GetItemSprite(this);
[JsonIgnore] public ItemIcon Icon => ItemCollection.Active.GetItemIcon(this);
[JsonIgnore] public int Hash => $"{Id}.{Modifier?.Id}.{Modifier?.Level}".GetHashCode();
[JsonIgnore] public bool IsModified => Modifier != null && Modifier.Id != ItemModifier.None;
[JsonIgnore] public bool IsEquipment => Params.Type == ItemType.Helmet || Params.Type == ItemType.Armor || Params.Type == ItemType.Vest || Params.Type == ItemType.Bracers || Params.Type == ItemType.Leggings || Params.Type == ItemType.Weapon || Params.Type == ItemType.Shield;
[JsonIgnore] public bool IsArmor => Params.Type == ItemType.Helmet || Params.Type == ItemType.Armor || Params.Type == ItemType.Vest || Params.Type == ItemType.Bracers || Params.Type == ItemType.Leggings;
[JsonIgnore] public bool IsWeapon => Params.Type == ItemType.Weapon;
[JsonIgnore] public bool IsShield => Params.Type == ItemType.Shield;
[JsonIgnore] public bool IsDagger => Params.Class == ItemClass.Dagger;
[JsonIgnore] public bool IsSword => Params.Class == ItemClass.Sword;
[JsonIgnore] public bool IsAxe => Params.Class == ItemClass.Axe;
[JsonIgnore] public bool IsPickaxe => Params.Class == ItemClass.Pickaxe;
[JsonIgnore] public bool IsWand => Params.Class == ItemClass.Wand;
[JsonIgnore] public bool IsBlunt => Params.Class == ItemClass.Blunt;
[JsonIgnore] public bool IsLance => Params.Class == ItemClass.Lance;
[JsonIgnore] public bool IsMelee => Params.Type == ItemType.Weapon && Params.Class != ItemClass.Bow && Params.Class != ItemClass.Firearm;
[JsonIgnore] public bool IsBow => Params.Class == ItemClass.Bow;
[JsonIgnore] public bool IsFirearm => Params.Class == ItemClass.Firearm;
[JsonIgnore] public bool IsOneHanded => !IsTwoHanded;
[JsonIgnore] public bool IsTwoHanded => Params.Class == ItemClass.Bow || Params.Tags.Contains(ItemTag.TwoHanded);
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 01cf7f5172991a64ca1723e1869888d7
timeCreated: 1508494931
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 01cf7f5172991a64ca1723e1869888d7
timeCreated: 1508494931
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,83 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Newtonsoft.Json;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
/// <summary>
/// Represents generic item params (common for all items).
/// </summary>
[Serializable]
public class ItemParams
{
public string Id;
public int Level;
public ItemRarity Rarity;
public ItemType Type;
public ItemClass Class;
public List<ItemTag> Tags = new List<ItemTag>();
public List<Property> Properties = new List<Property>();
public int Price;
public int Weight;
public ItemMaterial Material;
public string IconId;
public string SpriteId;
public string Meta;
/// <summary>
/// Use this property to provide localization values for items.
/// </summary>
[JsonIgnore, NonSerialized] public List<LocalizedValue> Localization = new List<LocalizedValue>();
public char Grade => (char) (65 + Level);
public Property FindProperty(PropertyId id)
{
var target = Properties.SingleOrDefault(i => i.Id == id && i.Element == ElementId.Physic);
return target;
}
public Property FindProperty(PropertyId id, ElementId element)
{
var target = Properties.SingleOrDefault(i => i.Id == id && i.Element == element);
return target;
}
public string GetLocalizedName(string language)
{
var localized = Localization.SingleOrDefault(i => i.Language == language) ?? Localization.SingleOrDefault(i => i.Language == "English");
return localized == null ? Id : localized.Value;
}
public List<string> MetaToList()
{
return Meta.IsEmpty() ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(Meta);
}
public ItemParams Copy()
{
return new ItemParams
{
Id = Id,
Level = Level,
Rarity = Rarity,
Type = Type,
Class = Class,
Tags = Tags.ToList(),
Properties = Properties.Select(i => i.Copy()).ToList(),
Price = Price,
Weight = Weight,
Material = Material,
IconId = IconId,
SpriteId = SpriteId,
Meta = Meta
};
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Newtonsoft.Json;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
/// <summary>
/// Represents generic item params (common for all items).
/// </summary>
[Serializable]
public class ItemParams
{
public string Id;
public int Level;
public ItemRarity Rarity;
public ItemType Type;
public ItemClass Class;
public List<ItemTag> Tags = new List<ItemTag>();
public List<Property> Properties = new List<Property>();
public int Price;
public int Weight;
public ItemMaterial Material;
public string IconId;
public string SpriteId;
public string Meta;
/// <summary>
/// Use this property to provide localization values for items.
/// </summary>
[JsonIgnore, NonSerialized] public List<LocalizedValue> Localization = new List<LocalizedValue>();
public char Grade => (char) (65 + Level);
public Property FindProperty(PropertyId id)
{
var target = Properties.SingleOrDefault(i => i.Id == id && i.Element == ElementId.Physic);
return target;
}
public Property FindProperty(PropertyId id, ElementId element)
{
var target = Properties.SingleOrDefault(i => i.Id == id && i.Element == element);
return target;
}
public string GetLocalizedName(string language)
{
var localized = Localization.SingleOrDefault(i => i.Language == language) ?? Localization.SingleOrDefault(i => i.Language == "English");
return localized == null ? Id : localized.Value;
}
public List<string> MetaToList()
{
return Meta.IsEmpty() ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(Meta);
}
public ItemParams Copy()
{
return new ItemParams
{
Id = Id,
Level = Level,
Rarity = Rarity,
Type = Type,
Class = Class,
Tags = Tags.ToList(),
Properties = Properties.Select(i => i.Copy()).ToList(),
Price = Price,
Weight = Weight,
Material = Material,
IconId = IconId,
SpriteId = SpriteId,
Meta = Meta
};
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 5f035382d1422314fb79b87287d6dbad
timeCreated: 1508494931
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 5f035382d1422314fb79b87287d6dbad
timeCreated: 1508494931
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,17 +1,17 @@
using System;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
[Serializable]
public class LocalizedValue
{
public string Language;
public string Value;
public LocalizedValue(string language, string value)
{
Language = language;
Value = value;
}
}
using System;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
[Serializable]
public class LocalizedValue
{
public string Language;
public string Value;
public LocalizedValue(string language, string value)
{
Language = language;
Value = value;
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: d8ef5b0ac3054d147bfab72638f28e88
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: d8ef5b0ac3054d147bfab72638f28e88
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,22 +1,22 @@
using System;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
[Serializable]
public class Modifier
{
public ItemModifier Id;
public int Level;
public Modifier()
{
}
public Modifier(ItemModifier id, int level)
{
Id = id;
Level = level;
}
}
using System;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
[Serializable]
public class Modifier
{
public ItemModifier Id;
public int Level;
public Modifier()
{
}
public Modifier(ItemModifier id, int level)
{
Id = id;
Level = level;
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 298c0d188a3892d45aa56a41de5ae22a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 298c0d188a3892d45aa56a41de5ae22a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,160 +1,160 @@
using System;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
/// <summary>
/// Represents key-value pair for storing item params.
/// Supported value formats:
/// "[VALUE]"
/// "[VALUE_MIN]-[VALUE_MAX]"
/// "[VALUE]/[ELEMENT]"
/// "[VALUE]/[ELEMENT]/[DURATION]"
/// </summary>
[Serializable]
public class Property
{
public PropertyId Id;
public string Value;
[HideInInspector] [NonSerialized] public int ValueInt;
[HideInInspector] [NonSerialized] public int Min;
[HideInInspector] [NonSerialized] public int Max;
[HideInInspector] [NonSerialized] public int Duration;
[HideInInspector] [NonSerialized] public ElementId Element;
[HideInInspector] [NonSerialized] public bool Percentage;
public Property()
{
}
public Property(PropertyId id, object value)
{
Id = id;
Value = value.ToString();
ParseValue();
}
public void ParseValue()
{
var parts = Value.Split('/');
if (Id == PropertyId.Damage || Id == PropertyId.Resistance)
{
switch (parts.Length)
{
case 2:
Element = parts[1].ToEnum<ElementId>();
break;
case 3:
Element = parts[1].ToEnum<ElementId>();
Duration = int.Parse(parts[2]);
break;
default:
Element = ElementId.Physic;
break;
}
}
if (Regex.IsMatch(parts[0], @"^\d+-\d+$"))
{
parts = parts[0].Split('-');
Min = int.Parse(parts[0]);
Max = int.Parse(parts[1]);
}
else if (parts[0].EndsWith("%"))
{
ValueInt = int.Parse(parts[0].Replace("%", null));
Percentage = true;
}
else
{
if (int.TryParse(parts[0], out var valueInt))
{
ValueInt = valueInt;
}
}
}
public void ReplaceValue(string value)
{
Value = value;
ParseValue();
}
public void ReplaceValue(float value)
{
ReplaceValue(Mathf.RoundToInt(value));
}
public void ReplaceValue(int value)
{
Value = value.ToString();
ParseValue();
}
public void Add(float value)
{
Add(Mathf.RoundToInt(value));
}
public void Add(int value)
{
if (Min > 0)
{
Min += value;
Max += value;
Value = $"{Min}-{Max}" + (Element == ElementId.Physic ? null : "/" + Element);
}
else
{
ValueInt += value;
Value = ValueInt + (Element == ElementId.Physic ? null : "/" + Element);
}
}
public void AddInPercentage(float value)
{
if (Min > 0)
{
Min = Mathf.RoundToInt(Min * (1 + value / 100f));
Max = Mathf.RoundToInt(Max * (1 + value / 100f));
Value = $"{Min}-{Max}" + (Element == ElementId.Physic ? null : "/" + Element);
}
else
{
ValueInt = Mathf.RoundToInt(ValueInt * (1 + value / 100f));
Value = ValueInt + (Element == ElementId.Physic ? null : "/" + Element);
}
}
public static Property Parse(string value)
{
var parts = value.Split('=');
var property = new Property
{
Id = parts[0].ToEnum<PropertyId>(),
Value = parts[1]
};
property.ParseValue();
return property;
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
ParseValue();
}
public Property Copy()
{
return new Property(Id, Value);
}
}
using System;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Data
{
/// <summary>
/// Represents key-value pair for storing item params.
/// Supported value formats:
/// "[VALUE]"
/// "[VALUE_MIN]-[VALUE_MAX]"
/// "[VALUE]/[ELEMENT]"
/// "[VALUE]/[ELEMENT]/[DURATION]"
/// </summary>
[Serializable]
public class Property
{
public PropertyId Id;
public string Value;
[HideInInspector] [NonSerialized] public int ValueInt;
[HideInInspector] [NonSerialized] public int Min;
[HideInInspector] [NonSerialized] public int Max;
[HideInInspector] [NonSerialized] public int Duration;
[HideInInspector] [NonSerialized] public ElementId Element;
[HideInInspector] [NonSerialized] public bool Percentage;
public Property()
{
}
public Property(PropertyId id, object value)
{
Id = id;
Value = value.ToString();
ParseValue();
}
public void ParseValue()
{
var parts = Value.Split('/');
if (Id == PropertyId.Damage || Id == PropertyId.Resistance)
{
switch (parts.Length)
{
case 2:
Element = parts[1].ToEnum<ElementId>();
break;
case 3:
Element = parts[1].ToEnum<ElementId>();
Duration = int.Parse(parts[2]);
break;
default:
Element = ElementId.Physic;
break;
}
}
if (Regex.IsMatch(parts[0], @"^\d+-\d+$"))
{
parts = parts[0].Split('-');
Min = int.Parse(parts[0]);
Max = int.Parse(parts[1]);
}
else if (parts[0].EndsWith("%"))
{
ValueInt = int.Parse(parts[0].Replace("%", null));
Percentage = true;
}
else
{
if (int.TryParse(parts[0], out var valueInt))
{
ValueInt = valueInt;
}
}
}
public void ReplaceValue(string value)
{
Value = value;
ParseValue();
}
public void ReplaceValue(float value)
{
ReplaceValue(Mathf.RoundToInt(value));
}
public void ReplaceValue(int value)
{
Value = value.ToString();
ParseValue();
}
public void Add(float value)
{
Add(Mathf.RoundToInt(value));
}
public void Add(int value)
{
if (Min > 0)
{
Min += value;
Max += value;
Value = $"{Min}-{Max}" + (Element == ElementId.Physic ? null : "/" + Element);
}
else
{
ValueInt += value;
Value = ValueInt + (Element == ElementId.Physic ? null : "/" + Element);
}
}
public void AddInPercentage(float value)
{
if (Min > 0)
{
Min = Mathf.RoundToInt(Min * (1 + value / 100f));
Max = Mathf.RoundToInt(Max * (1 + value / 100f));
Value = $"{Min}-{Max}" + (Element == ElementId.Physic ? null : "/" + Element);
}
else
{
ValueInt = Mathf.RoundToInt(ValueInt * (1 + value / 100f));
Value = ValueInt + (Element == ElementId.Physic ? null : "/" + Element);
}
}
public static Property Parse(string value)
{
var parts = value.Split('=');
var property = new Property
{
Id = parts[0].ToEnum<PropertyId>(),
Value = parts[1]
};
property.ParseValue();
return property;
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
ParseValue();
}
public Property Copy()
{
return new Property(Id, Value);
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 79c1405f54e6a5947b6a79f23714d5a4
timeCreated: 1508511989
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 79c1405f54e6a5947b6a79f23714d5a4
timeCreated: 1508511989
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +1,8 @@
fileFormatVersion: 2
guid: 3a20425a31584a94299c59d7d2609dc9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 3a20425a31584a94299c59d7d2609dc9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,145 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Helpers;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents hero (player) equipment. Based on equipment slots.
/// </summary>
public class Equipment : ItemContainer
{
public Action OnRefresh;
/// <summary>
/// Defines what kinds of items can be equipped.
/// </summary>
public List<ItemSlot> Slots;
/// <summary>
/// Equipped items will be instantiated in front of equipment slots.
/// </summary>
public GameObject ItemPrefab;
/// <summary>
/// Character preview.
/// </summary>
public Character Preview;
public Transform Scheme;
public int BagSize;
public readonly List<InventoryItem> InventoryItems = new List<InventoryItem>();
public void OnValidate()
{
if (Application.isPlaying) return;
Slots = GetComponentsInChildren<ItemSlot>(true).ToList();
//if (Character == null)
//{
// Character = FindObjectOfType<Character>();
//}
}
public void Start()
{
//Character.Animator.SetBool("Ready", false);
}
public void SetBagSize(int size)
{
BagSize = size;
var supplies = GetComponentsInChildren<ItemSlot>(true).Where(i => i.Types.Contains(ItemType.Supply)).ToList();
for (var i = 0; i < supplies.Count; i++)
{
supplies[i].Locked = i >= size;
}
}
public bool SelectAny()
{
if (InventoryItems.Count > 0)
{
InventoryItems[0].Select(true);
return true;
}
return false;
}
public override void Refresh(Item selected)
{
var items = Slots.Select(FindItem).Where(i => i != null).ToList();
var toggleGroup = GetComponentInParent<ToggleGroup>(includeInactive: true);
Reset();
foreach (var slot in Slots)
{
var item = FindItem(slot);
slot.gameObject.SetActive(item == null);
if (item == null) continue;
var inventoryItem = Instantiate(ItemPrefab, slot.transform.parent).GetComponent<InventoryItem>();
inventoryItem.Initialize(item, toggleGroup);
inventoryItem.Count.text = null;
inventoryItem.transform.position = slot.transform.position;
inventoryItem.transform.SetSiblingIndex(slot.transform.GetSiblingIndex());
if (AutoSelect) inventoryItem.Select(item == selected);
InventoryItems.Add(inventoryItem);
}
if (Preview)
{
CharacterInventorySetup.Setup(Preview, items);
Preview.Initialize();
}
OnRefresh?.Invoke();
}
private void Reset()
{
foreach (var inventoryItem in InventoryItems)
{
Destroy(inventoryItem.gameObject);
}
InventoryItems.Clear();
}
private Item FindItem(ItemSlot slot)
{
if (slot.Types.Contains(ItemType.Shield))
{
var copy = Items.SingleOrDefault(i => i.Params.Type == ItemType.Weapon && (i.IsTwoHanded || i.IsFirearm));
if (copy != null)
{
return copy;
}
}
var index = Slots.Where(i => i.Types.SequenceEqual(slot.Types)).ToList().IndexOf(slot);
var items = Items.Where(slot.Supports).ToList();
return index < items.Count ? items[index] : null;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Helpers;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents hero (player) equipment. Based on equipment slots.
/// </summary>
public class Equipment : ItemContainer
{
public Action OnRefresh;
/// <summary>
/// Defines what kinds of items can be equipped.
/// </summary>
public List<ItemSlot> Slots;
/// <summary>
/// Equipped items will be instantiated in front of equipment slots.
/// </summary>
public GameObject ItemPrefab;
/// <summary>
/// Character preview.
/// </summary>
public Character Preview;
public Transform Scheme;
public int BagSize;
public readonly List<InventoryItem> InventoryItems = new List<InventoryItem>();
public void OnValidate()
{
if (Application.isPlaying) return;
Slots = GetComponentsInChildren<ItemSlot>(true).ToList();
//if (Character == null)
//{
// Character = FindObjectOfType<Character>();
//}
}
public void Start()
{
//Character.Animator.SetBool("Ready", false);
}
public void SetBagSize(int size)
{
BagSize = size;
var supplies = GetComponentsInChildren<ItemSlot>(true).Where(i => i.Types.Contains(ItemType.Supply)).ToList();
for (var i = 0; i < supplies.Count; i++)
{
supplies[i].Locked = i >= size;
}
}
public bool SelectAny()
{
if (InventoryItems.Count > 0)
{
InventoryItems[0].Select(true);
return true;
}
return false;
}
public override void Refresh(Item selected)
{
var items = Slots.Select(FindItem).Where(i => i != null).ToList();
var toggleGroup = GetComponentInParent<ToggleGroup>(includeInactive: true);
Reset();
foreach (var slot in Slots)
{
var item = FindItem(slot);
slot.gameObject.SetActive(item == null);
if (item == null) continue;
var inventoryItem = Instantiate(ItemPrefab, slot.transform.parent).GetComponent<InventoryItem>();
inventoryItem.Initialize(item, toggleGroup);
inventoryItem.Count.text = null;
inventoryItem.transform.position = slot.transform.position;
inventoryItem.transform.SetSiblingIndex(slot.transform.GetSiblingIndex());
if (AutoSelect) inventoryItem.Select(item == selected);
InventoryItems.Add(inventoryItem);
}
if (Preview)
{
CharacterInventorySetup.Setup(Preview, items);
Preview.Initialize();
}
OnRefresh?.Invoke();
}
private void Reset()
{
foreach (var inventoryItem in InventoryItems)
{
Destroy(inventoryItem.gameObject);
}
InventoryItems.Clear();
}
private Item FindItem(ItemSlot slot)
{
if (slot.Types.Contains(ItemType.Shield))
{
var copy = Items.SingleOrDefault(i => i.Params.Type == ItemType.Weapon && (i.IsTwoHanded || i.IsFirearm));
if (copy != null)
{
return copy;
}
}
var index = Slots.Where(i => i.Types.SequenceEqual(slot.Types)).ToList().IndexOf(slot);
var items = Items.Where(slot.Supports).ToList();
return index < items.Count ? items[index] : null;
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: a0b571b9054039e4599e0d695cdcab42
timeCreated: 1508495828
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: a0b571b9054039e4599e0d695cdcab42
timeCreated: 1508495828
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,201 +1,201 @@
using System;
using System.Collections;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents inventory item and handles drag & drop operations.
/// </summary>
public class InventoryItem : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
[Header("Main")]
public Image Icon;
public Image Background;
public Image Frame;
public Text Count;
public Toggle Toggle;
[Header("Extra")]
public Sprite IconEmpty;
public Sprite IconMissed;
public Image Comparer;
public Image Fragment;
public GameObject Modificator;
public Text ModificatorText;
public Item Item { get; private set; }
private Action _scheduled;
private float _clickTime;
/// <summary>
/// These actions should be set when inventory UI is opened.
/// </summary>
public static Action<Item> OnLeftClick;
public static Action<Item> OnRightClick;
public static Action<Item> OnDoubleClick;
public static Action<Item> OnMouseEnter;
public static Action<Item> OnMouseExit;
public void OnEnable()
{
if (_scheduled != null)
{
StartCoroutine(ExecuteScheduled());
}
}
public void Initialize(Item item, ToggleGroup toggleGroup = null)
{
Item = item;
if (Item == null)
{
Reset();
return;
}
Icon.enabled = true;
Icon.sprite = item.Id == null ? IconEmpty : ItemCollection.Active.GetItemIcon(Item)?.Sprite ?? IconMissed;
Background.sprite = ItemCollection.Active.GetBackground(Item) ?? ItemCollection.Active.BackgroundBrown;
Background.color = Color.white;
Frame.raycastTarget = true;
if (Count)
{
Count.SetActive(true);
Count.text = item.Count.ToString();
}
if (Fragment)
{
Fragment.SetActive(true);
Fragment.SetActive(Item.Params.Type == ItemType.Fragment);
}
if (Toggle)
{
Toggle.group = toggleGroup ?? GetComponentInParent<ToggleGroup>();
}
if (Modificator)
{
var mod = Item.Modifier != null && Item.Modifier.Id != ItemModifier.None;
Modificator.SetActive(mod);
if (mod)
{
string text;
switch (Item.Modifier.Id)
{
case ItemModifier.LevelDown: text = "G-"; break;
case ItemModifier.LevelUp: text = "G+"; break;
default: text = Item.Modifier.Id.ToString().ToUpper()[0].ToString(); break;
}
ModificatorText.text = text;
}
}
}
public void Reset()
{
Icon.enabled = false;
Icon.sprite = null;
Background.sprite = ItemCollection.Active.BackgroundBrown ?? Background.sprite;
Background.color = new Color32(150, 150, 150, 255);
Frame.raycastTarget = false;
if (Count) Count.SetActive(false);
if (Toggle) { Toggle.group = null; Toggle.SetIsOnWithoutNotify(false); }
if (Modificator) Modificator.SetActive(false);
if (Comparer) Comparer.SetActive(false);
if (Fragment) Fragment.SetActive(false);
}
public void OnPointerClick(PointerEventData eventData)
{
OnPointerClick(eventData.button);
}
public void OnPointerEnter(PointerEventData eventData)
{
OnMouseEnter?.Invoke(Item);
}
public void OnPointerExit(PointerEventData eventData)
{
OnMouseExit?.Invoke(Item);
}
public void OnPointerClick(PointerEventData.InputButton button)
{
if (button == PointerEventData.InputButton.Left)
{
OnLeftClick?.Invoke(Item);
var delta = Mathf.Abs(Time.time - _clickTime);
if (delta < 0.5f) // If double click.
{
_clickTime = 0;
if (OnDoubleClick != null)
{
StartCoroutine(ExecuteInNextUpdate(() => OnDoubleClick(Item)));
}
}
else
{
_clickTime = Time.time;
}
}
else if (button == PointerEventData.InputButton.Right)
{
OnRightClick?.Invoke(Item);
}
}
private static IEnumerator ExecuteInNextUpdate(Action action)
{
yield return null;
action();
}
public void Select(bool selected)
{
if (Toggle == null) return;
if (gameObject.activeInHierarchy || !selected)
{
Toggle.isOn = selected;
}
else
{
_scheduled = () => Toggle.isOn = true;
}
if (selected)
{
OnLeftClick?.Invoke(Item);
}
}
private IEnumerator ExecuteScheduled()
{
yield return null;
_scheduled();
_scheduled = null;
}
}
using System;
using System.Collections;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents inventory item and handles drag & drop operations.
/// </summary>
public class InventoryItem : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
[Header("Main")]
public Image Icon;
public Image Background;
public Image Frame;
public Text Count;
public Toggle Toggle;
[Header("Extra")]
public Sprite IconEmpty;
public Sprite IconMissed;
public Image Comparer;
public Image Fragment;
public GameObject Modificator;
public Text ModificatorText;
public Item Item { get; private set; }
private Action _scheduled;
private float _clickTime;
/// <summary>
/// These actions should be set when inventory UI is opened.
/// </summary>
public static Action<Item> OnLeftClick;
public static Action<Item> OnRightClick;
public static Action<Item> OnDoubleClick;
public static Action<Item> OnMouseEnter;
public static Action<Item> OnMouseExit;
public void OnEnable()
{
if (_scheduled != null)
{
StartCoroutine(ExecuteScheduled());
}
}
public void Initialize(Item item, ToggleGroup toggleGroup = null)
{
Item = item;
if (Item == null)
{
Reset();
return;
}
Icon.enabled = true;
Icon.sprite = item.Id == null ? IconEmpty : ItemCollection.Active.GetItemIcon(Item)?.Sprite ?? IconMissed;
Background.sprite = ItemCollection.Active.GetBackground(Item) ?? ItemCollection.Active.BackgroundBrown;
Background.color = Color.white;
Frame.raycastTarget = true;
if (Count)
{
Count.SetActive(true);
Count.text = item.Count.ToString();
}
if (Fragment)
{
Fragment.SetActive(true);
Fragment.SetActive(Item.Params.Type == ItemType.Fragment);
}
if (Toggle)
{
Toggle.group = toggleGroup ?? GetComponentInParent<ToggleGroup>();
}
if (Modificator)
{
var mod = Item.Modifier != null && Item.Modifier.Id != ItemModifier.None;
Modificator.SetActive(mod);
if (mod)
{
string text;
switch (Item.Modifier.Id)
{
case ItemModifier.LevelDown: text = "G-"; break;
case ItemModifier.LevelUp: text = "G+"; break;
default: text = Item.Modifier.Id.ToString().ToUpper()[0].ToString(); break;
}
ModificatorText.text = text;
}
}
}
public void Reset()
{
Icon.enabled = false;
Icon.sprite = null;
Background.sprite = ItemCollection.Active.BackgroundBrown ?? Background.sprite;
Background.color = new Color32(150, 150, 150, 255);
Frame.raycastTarget = false;
if (Count) Count.SetActive(false);
if (Toggle) { Toggle.group = null; Toggle.SetIsOnWithoutNotify(false); }
if (Modificator) Modificator.SetActive(false);
if (Comparer) Comparer.SetActive(false);
if (Fragment) Fragment.SetActive(false);
}
public void OnPointerClick(PointerEventData eventData)
{
OnPointerClick(eventData.button);
}
public void OnPointerEnter(PointerEventData eventData)
{
OnMouseEnter?.Invoke(Item);
}
public void OnPointerExit(PointerEventData eventData)
{
OnMouseExit?.Invoke(Item);
}
public void OnPointerClick(PointerEventData.InputButton button)
{
if (button == PointerEventData.InputButton.Left)
{
OnLeftClick?.Invoke(Item);
var delta = Mathf.Abs(Time.time - _clickTime);
if (delta < 0.5f) // If double click.
{
_clickTime = 0;
if (OnDoubleClick != null)
{
StartCoroutine(ExecuteInNextUpdate(() => OnDoubleClick(Item)));
}
}
else
{
_clickTime = Time.time;
}
}
else if (button == PointerEventData.InputButton.Right)
{
OnRightClick?.Invoke(Item);
}
}
private static IEnumerator ExecuteInNextUpdate(Action action)
{
yield return null;
action();
}
public void Select(bool selected)
{
if (Toggle == null) return;
if (gameObject.activeInHierarchy || !selected)
{
Toggle.isOn = selected;
}
else
{
_scheduled = () => Toggle.isOn = true;
}
if (selected)
{
OnLeftClick?.Invoke(Item);
}
}
private IEnumerator ExecuteScheduled()
{
yield return null;
_scheduled();
_scheduled = null;
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: e0aafb945e34dad42af9accb93f787da
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: e0aafb945e34dad42af9accb93f787da
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,30 +1,30 @@
using System.Collections.Generic;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Abstract item container. It can be inventory bag, player equipment or trader goods.
/// </summary>
public abstract class ItemContainer : MonoBehaviour
{
/// <summary>
/// List of items.
/// </summary>
public List<Item> Items { get; protected set; } = new List<Item>();
[Header("Settings")]
[Tooltip("Stack identical inventory items to a single UI element.")]
public bool Stacked = true;
public bool AutoSelect = true;
public abstract void Refresh(Item selected);
public void Initialize(ref List<Item> items, Item selected = null)
{
Items = items;
Refresh(selected);
}
}
using System.Collections.Generic;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Abstract item container. It can be inventory bag, player equipment or trader goods.
/// </summary>
public abstract class ItemContainer : MonoBehaviour
{
/// <summary>
/// List of items.
/// </summary>
public List<Item> Items { get; protected set; } = new List<Item>();
[Header("Settings")]
[Tooltip("Stack identical inventory items to a single UI element.")]
public bool Stacked = true;
public bool AutoSelect = true;
public abstract void Refresh(Item selected);
public void Initialize(ref List<Item> items, Item selected = null)
{
Items = items;
Refresh(selected);
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: cba7422e860e3ac42ad3a70a98329be1
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: cba7422e860e3ac42ad3a70a98329be1
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,137 +1,137 @@
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents item when it was selected. Displays icon, name, price and properties.
/// </summary>
public class ItemInfo : MonoBehaviour
{
public GameObject Selection;
public GameObject Buttons;
public Text Name;
public Text Labels;
public Text Values;
public Text Price;
public Image Icon;
public Image Background;
public Item Item { get; protected set; }
protected static readonly List<PropertyId> Sorting = new List<PropertyId>
{
PropertyId.Damage,
PropertyId.StaminaMax,
PropertyId.Blocking,
PropertyId.Resistance
};
public void OnEnable()
{
if (Item == null)
{
Reset();
}
}
public void Reset()
{
Selection.SetActive(false);
Buttons.SetActive(false);
if (Name) Name.text = null;
if (Labels) Labels.text = null;
if (Values) Values.text = null;
if (Price) Price.text = null;
}
public virtual void Initialize(Item item, int price, bool trader = false)
{
Item = item;
if (item == null)
{
Reset();
return;
}
Selection.SetActive(true);
Buttons.SetActive(true);
Name.text = item.Params.GetLocalizedName(Application.systemLanguage.ToString());
Icon.sprite = ItemCollection.Active.FindIcon(item.Params.IconId);
Background.sprite = ItemCollection.Active.GetBackground(item);
UpdatePrice(item, price, trader);
var main = new List<object> { item.Params.Type };
if (item.Params.Class != ItemClass.Undefined) main.Add(item.Params.Class);
foreach (var t in item.Params.Tags)
{
main.Add(t);
}
var dict = new Dictionary<string, object> { { "ItemInfo.Type", string.Join(" / ", main) } };
if (item.Params.Level >= 0) dict.Add("ItemInfo.Level", item.Params.Level);
if (item.Modifier != null)
{
dict.Add("ItemInfo.Modifier", $"{item.Modifier.Id} [{item.Modifier.Level}]");
}
var props = item.Params.Properties.ToList().OrderBy(i => { var index = Sorting.IndexOf(i.Id); return index == -1 ? 999 : index; }).ToList();
foreach (var p in props)
{
switch (p.Id)
{
case PropertyId.Damage:
dict.Add($"ItemInfo.{p.Id}", $"{p.Min}-{p.Max}");
break;
case PropertyId.CriticalChance:
case PropertyId.CriticalDamage:
dict.Add($"ItemInfo.{p.Id}", $"+{p.Value}%");
break;
case PropertyId.ChargeTimings:
dict.Add($"ItemInfo.{p.Id}", $"{p.Value.Split(',').Length}");
break;
default:
dict.Add($"ItemInfo.{p.Id}", $"{p.Value}");
break;
}
}
dict.Add("ItemInfo.Weight", $"{item.Params.Weight / 10f:0.##} kg");
if (Price && item.Params.Type != ItemType.Currency)
{
dict.Add("ItemInfo.Price", $"{item.Params.Price} gold");
}
Labels.text = string.Join("\n", dict.Keys);
Values.text = string.Join("\n", dict.Values);
}
public virtual void UpdatePrice(Item item, int price, bool trader)
{
if (!Price) return;
if (item.Params.Type == ItemType.Currency)
{
Price.text = null;
}
else
{
Price.text = trader ? $"Buy price: {price}G" : $"Sell price: {price}G";
}
}
}
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents item when it was selected. Displays icon, name, price and properties.
/// </summary>
public class ItemInfo : MonoBehaviour
{
public GameObject Selection;
public GameObject Buttons;
public Text Name;
public Text Labels;
public Text Values;
public Text Price;
public Image Icon;
public Image Background;
public Item Item { get; protected set; }
protected static readonly List<PropertyId> Sorting = new List<PropertyId>
{
PropertyId.Damage,
PropertyId.StaminaMax,
PropertyId.Blocking,
PropertyId.Resistance
};
public void OnEnable()
{
if (Item == null)
{
Reset();
}
}
public void Reset()
{
Selection.SetActive(false);
Buttons.SetActive(false);
if (Name) Name.text = null;
if (Labels) Labels.text = null;
if (Values) Values.text = null;
if (Price) Price.text = null;
}
public virtual void Initialize(Item item, int price, bool trader = false)
{
Item = item;
if (item == null)
{
Reset();
return;
}
Selection.SetActive(true);
Buttons.SetActive(true);
Name.text = item.Params.GetLocalizedName(Application.systemLanguage.ToString());
Icon.sprite = ItemCollection.Active.FindIcon(item.Params.IconId);
Background.sprite = ItemCollection.Active.GetBackground(item);
UpdatePrice(item, price, trader);
var main = new List<object> { item.Params.Type };
if (item.Params.Class != ItemClass.Undefined) main.Add(item.Params.Class);
foreach (var t in item.Params.Tags)
{
main.Add(t);
}
var dict = new Dictionary<string, object> { { "ItemInfo.Type", string.Join(" / ", main) } };
if (item.Params.Level >= 0) dict.Add("ItemInfo.Level", item.Params.Level);
if (item.Modifier != null)
{
dict.Add("ItemInfo.Modifier", $"{item.Modifier.Id} [{item.Modifier.Level}]");
}
var props = item.Params.Properties.ToList().OrderBy(i => { var index = Sorting.IndexOf(i.Id); return index == -1 ? 999 : index; }).ToList();
foreach (var p in props)
{
switch (p.Id)
{
case PropertyId.Damage:
dict.Add($"ItemInfo.{p.Id}", $"{p.Min}-{p.Max}");
break;
case PropertyId.CriticalChance:
case PropertyId.CriticalDamage:
dict.Add($"ItemInfo.{p.Id}", $"+{p.Value}%");
break;
case PropertyId.ChargeTimings:
dict.Add($"ItemInfo.{p.Id}", $"{p.Value.Split(',').Length}");
break;
default:
dict.Add($"ItemInfo.{p.Id}", $"{p.Value}");
break;
}
}
dict.Add("ItemInfo.Weight", $"{item.Params.Weight / 10f:0.##} kg");
if (Price && item.Params.Type != ItemType.Currency)
{
dict.Add("ItemInfo.Price", $"{item.Params.Price} gold");
}
Labels.text = string.Join("\n", dict.Keys);
Values.text = string.Join("\n", dict.Values);
}
public virtual void UpdatePrice(Item item, int price, bool trader)
{
if (!Price) return;
if (item.Params.Type == ItemType.Currency)
{
Price.text = null;
}
else
{
Price.text = trader ? $"Buy price: {price}G" : $"Sell price: {price}G";
}
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 71a926fb72b5a4f438891452c4866688
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 71a926fb72b5a4f438891452c4866688
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,36 +1,36 @@
using System.Collections.Generic;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents equipment slot. Inventory items can be placed here.
/// </summary>
public class ItemSlot : MonoBehaviour
{
public Image Icon;
public Image Background;
public Sprite ActiveSprite;
public Sprite LockedSprite;
public List<ItemType> Types;
public List<ItemClass> Classes;
public bool Locked
{
get => Icon.sprite == LockedSprite;
set
{
Icon.sprite = value ? LockedSprite : ActiveSprite;
Background.color = value ? new Color32(150, 150, 150, 255) : new Color32(255, 255, 255, 255);
}
}
public bool Supports(Item item)
{
return Types.Contains(item.Params.Type) && (Classes.Count == 0 || Classes.Contains(item.Params.Class)) && !Locked;
}
}
using System.Collections.Generic;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Represents equipment slot. Inventory items can be placed here.
/// </summary>
public class ItemSlot : MonoBehaviour
{
public Image Icon;
public Image Background;
public Sprite ActiveSprite;
public Sprite LockedSprite;
public List<ItemType> Types;
public List<ItemClass> Classes;
public bool Locked
{
get => Icon.sprite == LockedSprite;
set
{
Icon.sprite = value ? LockedSprite : ActiveSprite;
Background.color = value ? new Color32(150, 150, 150, 255) : new Color32(255, 255, 255, 255);
}
}
public bool Supports(Item item)
{
return Types.Contains(item.Params.Type) && (Classes.Count == 0 || Classes.Contains(item.Params.Class)) && !Locked;
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: c75e3a26bedbcb147bcb8f02343721f3
timeCreated: 1508495903
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: c75e3a26bedbcb147bcb8f02343721f3
timeCreated: 1508495903
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,95 +1,95 @@
using System;
using System.Linq;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Abstract item workspace. It can be shop or player inventory. Items can be managed here (selected, moved and so on).
/// </summary>
public abstract class ItemWorkspace : MonoBehaviour
{
public ItemCollection ItemCollection;
public ItemInfo ItemInfo;
public static float SfxVolume = 1;
public Item SelectedItem { get; protected set; }
public abstract void Refresh();
protected void Reset()
{
SelectedItem = null;
ItemInfo.Reset();
}
protected void MoveItem(Item item, ItemContainer from, ItemContainer to, int amount = 1, string currencyId = null)
{
MoveItemSilent(item, from, to, amount);
var moved = to.Items.Last(i => i.Hash == item.Hash);
if (from.Stacked)
{
if (item.Count == 0)
{
SelectedItem = currencyId == null ? moved : from.Items.Single(i => i.Id == currencyId);
}
}
else
{
SelectedItem = from.Items.LastOrDefault(i => i.Hash == item.Hash) ?? moved;
}
Refresh();
from.Refresh(SelectedItem);
to.Refresh(SelectedItem);
}
public void MoveItemSilent(Item item, ItemContainer from, ItemContainer to, int amount = 1)
{
if (item.Count <= 0) throw new ArgumentException("item.Count <= 0");
if (amount <= 0) throw new ArgumentException("amount <= 0");
if (item.Count < amount) throw new ArgumentException("item.Count < amount");
if (to.Stacked)
{
var targets = to.Items.Where(i => i.Hash == item.Hash).ToList();
switch (targets.Count)
{
case 0:
to.Items.Add(new Item(item.Id, item.Modifier, amount));
break;
case 1:
targets[0].Count += amount;
break;
default:
throw new Exception($"Unable to move item silently: {item.Id} ({item.Hash}).");
}
}
else
{
to.Items.Add(new Item(item.Id, item.Modifier, amount));
}
var moved = to.Items.Last(i => i.Hash == item.Hash);
if (from.Stacked)
{
item.Count -= amount;
if (item.Count == 0)
{
from.Items.Remove(item);
}
}
else
{
from.Items.Remove(item);
}
}
}
using System;
using System.Linq;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Abstract item workspace. It can be shop or player inventory. Items can be managed here (selected, moved and so on).
/// </summary>
public abstract class ItemWorkspace : MonoBehaviour
{
public ItemCollection ItemCollection;
public ItemInfo ItemInfo;
public static float SfxVolume = 1;
public Item SelectedItem { get; protected set; }
public abstract void Refresh();
protected void Reset()
{
SelectedItem = null;
ItemInfo.Reset();
}
protected void MoveItem(Item item, ItemContainer from, ItemContainer to, int amount = 1, string currencyId = null)
{
MoveItemSilent(item, from, to, amount);
var moved = to.Items.Last(i => i.Hash == item.Hash);
if (from.Stacked)
{
if (item.Count == 0)
{
SelectedItem = currencyId == null ? moved : from.Items.Single(i => i.Id == currencyId);
}
}
else
{
SelectedItem = from.Items.LastOrDefault(i => i.Hash == item.Hash) ?? moved;
}
Refresh();
from.Refresh(SelectedItem);
to.Refresh(SelectedItem);
}
public void MoveItemSilent(Item item, ItemContainer from, ItemContainer to, int amount = 1)
{
if (item.Count <= 0) throw new ArgumentException("item.Count <= 0");
if (amount <= 0) throw new ArgumentException("amount <= 0");
if (item.Count < amount) throw new ArgumentException("item.Count < amount");
if (to.Stacked)
{
var targets = to.Items.Where(i => i.Hash == item.Hash).ToList();
switch (targets.Count)
{
case 0:
to.Items.Add(new Item(item.Id, item.Modifier, amount));
break;
case 1:
targets[0].Count += amount;
break;
default:
throw new Exception($"Unable to move item silently: {item.Id} ({item.Hash}).");
}
}
else
{
to.Items.Add(new Item(item.Id, item.Modifier, amount));
}
var moved = to.Items.Last(i => i.Hash == item.Hash);
if (from.Stacked)
{
item.Count -= amount;
if (item.Count == 0)
{
from.Items.Remove(item);
}
}
else
{
from.Items.Remove(item);
}
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 8bce2241fefb191448ef9c30f3ad750a
timeCreated: 1508495107
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 8bce2241fefb191448ef9c30f3ad750a
timeCreated: 1508495107
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,249 +1,249 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Scrollable item container that can display item list. Automatic vertical scrolling.
/// </summary>
public class ScrollInventory : ItemContainer
{
[Tooltip("Sort items automatically using SortingFunc (can be redefined).")]
public bool AutoSorting;
[Tooltip("Add an extra empty row or a column at the end.")]
public bool Extend;
[Header("UI")]
public ScrollRect ScrollRect;
public GridLayoutGroup Grid;
public InventoryItem ItemPrefab;
public Func<Item, int> SortingFunc = item => TypePriority.IndexOf(item.Params.Type); // You can override this.
public Func<Item, bool> FilterFunc; // You can override this.
public Action OnRefresh;
#if TAP_HEROES
public TMPro.TextMeshProUGUI Gold;
#endif
private static readonly List<ItemType> TypePriority = new List<ItemType>
{
ItemType.Currency,
ItemType.Container,
ItemType.Booster,
ItemType.Supply,
ItemType.Weapon,
ItemType.Helmet,
ItemType.Armor,
ItemType.Vest,
ItemType.Bracers,
ItemType.Leggings,
ItemType.Shield,
ItemType.Fragment,
ItemType.Backpack,
ItemType.Jewelry,
ItemType.Loot,
ItemType.Recipe,
ItemType.Material
};
private readonly List<InventoryItem> _itemInstances = new List<InventoryItem>(); // Reusing instances to reduce Instantiate() calls.
public void Initialize(ref List<Item> items, Item selected, bool reset = false)
{
base.Initialize(ref items, selected);
}
public void Initialize(ref List<Item> items)
{
base.Initialize(ref items);
ResetNormalizedPosition();
}
public void SelectItem(Item item)
{
_itemInstances.FirstOrDefault(i => i.Item == item)?.Select(true);
}
public bool SelectAny()
{
var any = _itemInstances.FirstOrDefault(i => i.Item != null);
if (any == null) return false;
any.Select(true);
return true;
}
public void SetTypeFilter(string input)
{
var type = input.ToEnum<ItemType>();
SetTypeFilter(new List<ItemType> { type });
}
public void SetTypeFilter(List<ItemType> types)
{
FilterFunc = item => types.Contains(item.Params.Type);
Refresh(null);
}
public void UnsetFilter()
{
FilterFunc = null;
Refresh(null);
}
public override void Refresh(Item selected)
{
if (Items == null) return;
List<Item> items;
if (AutoSorting && SortingFunc != null)
{
items = new List<Item>();
var groups = Items.OrderBy(SortingFunc).ToList().GroupBy(i => i.Params.Type);
foreach (var group in groups)
{
items.AddRange(group.OrderBy(i => i.Params.Class).ThenBy(i => i.Params.Price));
}
}
else
{
items = Items.ToList();
}
if (FilterFunc != null)
{
items.RemoveAll(i => !FilterFunc(i));
}
foreach (var instance in _itemInstances)
{
instance.Reset();
instance.SetActive(false);
}
var toggleGroup = GetComponentInParent<ToggleGroup>(includeInactive: true);
for (var i = 0; i < items.Count; i++)
{
var instance = GetItemInstance();
instance.transform.SetSiblingIndex(i);
instance.Initialize(items[i], toggleGroup);
instance.Count.SetActive(Stacked);
if (AutoSelect) instance.Select(items[i] == selected);
}
var columns = 0;
var rows = 0;
switch (Grid.constraint)
{
case GridLayoutGroup.Constraint.FixedColumnCount:
{
var height = Mathf.FloorToInt((ScrollRect.GetComponent<RectTransform>().rect.height + Grid.spacing.y) / (Grid.cellSize.y + Grid.spacing.y));
columns = Grid.constraintCount;
rows = Mathf.Max(height, Mathf.FloorToInt((float) items.Count / columns));
if (Extend) rows++;
break;
}
case GridLayoutGroup.Constraint.FixedRowCount:
{
var width = Mathf.FloorToInt((ScrollRect.GetComponent<RectTransform>().rect.width + Grid.spacing.x) / (Grid.cellSize.x + Grid.spacing.x));
rows = Grid.constraintCount;
columns = Mathf.Max(width, Mathf.FloorToInt((float) items.Count / rows));
if (Extend) columns++;
break;
}
}
for (var i = items.Count; i < columns * rows; i++)
{
var instance = GetItemInstance();
instance.Initialize(null);
}
OnRefresh?.Invoke();
#if TAP_HEROES
var gold = Items.Where(i => i.Id == "Gold").Sum(i => i.Count);
Gold?.SetText($"{gold} <sprite=0>");
TapHeroes.Scripts.Interface.Elements.ItemComparer.Compare(_itemInstances);
#endif
}
private InventoryItem GetItemInstance()
{
var instance = _itemInstances.FirstOrDefault(i => !i.gameObject.activeSelf);
if (instance == null)
{
instance = Instantiate(ItemPrefab, Grid.transform);
_itemInstances.Add(instance);
}
else
{
instance.gameObject.SetActive(true);
}
return instance;
}
public InventoryItem FindItem(Item item)
{
return _itemInstances.SingleOrDefault(i => i.gameObject.activeSelf && i.Item != null && i.Item.Hash == item.Hash);
}
public InventoryItem FindItem(string itemId)
{
return _itemInstances.SingleOrDefault(i => i.gameObject.activeSelf && i.Item != null && i.Item.Id == itemId);
}
public void ResetNormalizedPosition()
{
if (ScrollRect.horizontal) ScrollRect.horizontalNormalizedPosition = 0;
if (ScrollRect.vertical) ScrollRect.verticalNormalizedPosition = 1;
}
public IEnumerator SnapTo(RectTransform target, bool horizontal = true, bool vertical = true)
{
yield return null;
Canvas.ForceUpdateCanvases();
var pos = (Vector2) ScrollRect.transform.InverseTransformPoint(ScrollRect.content.position) - (Vector2) ScrollRect.transform.InverseTransformPoint(target.position);
if (!horizontal) pos.x = ScrollRect.content.anchoredPosition.x;
if (!vertical) pos.y = ScrollRect.content.anchoredPosition.y;
ScrollRect.content.anchoredPosition = pos;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
/// <summary>
/// Scrollable item container that can display item list. Automatic vertical scrolling.
/// </summary>
public class ScrollInventory : ItemContainer
{
[Tooltip("Sort items automatically using SortingFunc (can be redefined).")]
public bool AutoSorting;
[Tooltip("Add an extra empty row or a column at the end.")]
public bool Extend;
[Header("UI")]
public ScrollRect ScrollRect;
public GridLayoutGroup Grid;
public InventoryItem ItemPrefab;
public Func<Item, int> SortingFunc = item => TypePriority.IndexOf(item.Params.Type); // You can override this.
public Func<Item, bool> FilterFunc; // You can override this.
public Action OnRefresh;
#if TAP_HEROES
public TMPro.TextMeshProUGUI Gold;
#endif
private static readonly List<ItemType> TypePriority = new List<ItemType>
{
ItemType.Currency,
ItemType.Container,
ItemType.Booster,
ItemType.Supply,
ItemType.Weapon,
ItemType.Helmet,
ItemType.Armor,
ItemType.Vest,
ItemType.Bracers,
ItemType.Leggings,
ItemType.Shield,
ItemType.Fragment,
ItemType.Backpack,
ItemType.Jewelry,
ItemType.Loot,
ItemType.Recipe,
ItemType.Material
};
private readonly List<InventoryItem> _itemInstances = new List<InventoryItem>(); // Reusing instances to reduce Instantiate() calls.
public void Initialize(ref List<Item> items, Item selected, bool reset = false)
{
base.Initialize(ref items, selected);
}
public void Initialize(ref List<Item> items)
{
base.Initialize(ref items);
ResetNormalizedPosition();
}
public void SelectItem(Item item)
{
_itemInstances.FirstOrDefault(i => i.Item == item)?.Select(true);
}
public bool SelectAny()
{
var any = _itemInstances.FirstOrDefault(i => i.Item != null);
if (any == null) return false;
any.Select(true);
return true;
}
public void SetTypeFilter(string input)
{
var type = input.ToEnum<ItemType>();
SetTypeFilter(new List<ItemType> { type });
}
public void SetTypeFilter(List<ItemType> types)
{
FilterFunc = item => types.Contains(item.Params.Type);
Refresh(null);
}
public void UnsetFilter()
{
FilterFunc = null;
Refresh(null);
}
public override void Refresh(Item selected)
{
if (Items == null) return;
List<Item> items;
if (AutoSorting && SortingFunc != null)
{
items = new List<Item>();
var groups = Items.OrderBy(SortingFunc).ToList().GroupBy(i => i.Params.Type);
foreach (var group in groups)
{
items.AddRange(group.OrderBy(i => i.Params.Class).ThenBy(i => i.Params.Price));
}
}
else
{
items = Items.ToList();
}
if (FilterFunc != null)
{
items.RemoveAll(i => !FilterFunc(i));
}
foreach (var instance in _itemInstances)
{
instance.Reset();
instance.SetActive(false);
}
var toggleGroup = GetComponentInParent<ToggleGroup>(includeInactive: true);
for (var i = 0; i < items.Count; i++)
{
var instance = GetItemInstance();
instance.transform.SetSiblingIndex(i);
instance.Initialize(items[i], toggleGroup);
instance.Count.SetActive(Stacked);
if (AutoSelect) instance.Select(items[i] == selected);
}
var columns = 0;
var rows = 0;
switch (Grid.constraint)
{
case GridLayoutGroup.Constraint.FixedColumnCount:
{
var height = Mathf.FloorToInt((ScrollRect.GetComponent<RectTransform>().rect.height + Grid.spacing.y) / (Grid.cellSize.y + Grid.spacing.y));
columns = Grid.constraintCount;
rows = Mathf.Max(height, Mathf.FloorToInt((float) items.Count / columns));
if (Extend) rows++;
break;
}
case GridLayoutGroup.Constraint.FixedRowCount:
{
var width = Mathf.FloorToInt((ScrollRect.GetComponent<RectTransform>().rect.width + Grid.spacing.x) / (Grid.cellSize.x + Grid.spacing.x));
rows = Grid.constraintCount;
columns = Mathf.Max(width, Mathf.FloorToInt((float) items.Count / rows));
if (Extend) columns++;
break;
}
}
for (var i = items.Count; i < columns * rows; i++)
{
var instance = GetItemInstance();
instance.Initialize(null);
}
OnRefresh?.Invoke();
#if TAP_HEROES
var gold = Items.Where(i => i.Id == "Gold").Sum(i => i.Count);
Gold?.SetText($"{gold} <sprite=0>");
TapHeroes.Scripts.Interface.Elements.ItemComparer.Compare(_itemInstances);
#endif
}
private InventoryItem GetItemInstance()
{
var instance = _itemInstances.FirstOrDefault(i => !i.gameObject.activeSelf);
if (instance == null)
{
instance = Instantiate(ItemPrefab, Grid.transform);
_itemInstances.Add(instance);
}
else
{
instance.gameObject.SetActive(true);
}
return instance;
}
public InventoryItem FindItem(Item item)
{
return _itemInstances.SingleOrDefault(i => i.gameObject.activeSelf && i.Item != null && i.Item.Hash == item.Hash);
}
public InventoryItem FindItem(string itemId)
{
return _itemInstances.SingleOrDefault(i => i.gameObject.activeSelf && i.Item != null && i.Item.Id == itemId);
}
public void ResetNormalizedPosition()
{
if (ScrollRect.horizontal) ScrollRect.horizontalNormalizedPosition = 0;
if (ScrollRect.vertical) ScrollRect.verticalNormalizedPosition = 1;
}
public IEnumerator SnapTo(RectTransform target, bool horizontal = true, bool vertical = true)
{
yield return null;
Canvas.ForceUpdateCanvases();
var pos = (Vector2) ScrollRect.transform.InverseTransformPoint(ScrollRect.content.position) - (Vector2) ScrollRect.transform.InverseTransformPoint(target.position);
if (!horizontal) pos.x = ScrollRect.content.anchoredPosition.x;
if (!vertical) pos.y = ScrollRect.content.anchoredPosition.y;
ScrollRect.content.anchoredPosition = pos;
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: b1b2694827ea72749bfafba0579e6b8e
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: b1b2694827ea72749bfafba0579e6b8e
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,28 +1,28 @@
using System.Collections.Generic;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
public class ScrollInventoryFilter : MonoBehaviour
{
public ScrollInventory ScrollInventory;
public Toggle Weapon;
public Toggle Armor;
public Toggle Helmet;
public Toggle Shield;
public void OnSelect(bool value)
{
var types = new List<ItemType>();
if (Weapon.isOn) types.Add(ItemType.Weapon);
if (Armor.isOn) types.Add(ItemType.Armor);
if (Helmet.isOn) types.Add(ItemType.Helmet);
if (Shield.isOn) types.Add(ItemType.Shield);
ScrollInventory.SetTypeFilter(types);
}
}
using System.Collections.Generic;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Elements
{
public class ScrollInventoryFilter : MonoBehaviour
{
public ScrollInventory ScrollInventory;
public Toggle Weapon;
public Toggle Armor;
public Toggle Helmet;
public Toggle Shield;
public void OnSelect(bool value)
{
var types = new List<ItemType>();
if (Weapon.isOn) types.Add(ItemType.Weapon);
if (Armor.isOn) types.Add(ItemType.Armor);
if (Helmet.isOn) types.Add(ItemType.Helmet);
if (Shield.isOn) types.Add(ItemType.Shield);
ScrollInventory.SetTypeFilter(types);
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 4b21edc9891e9b243b69701a0b5656e1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 4b21edc9891e9b243b69701a0b5656e1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +1,8 @@
fileFormatVersion: 2
guid: 280493a052eaa744e8346e6baf1fd68c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 280493a052eaa744e8346e6baf1fd68c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,14 +1,14 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ElementId
{
Physic = 0,
Magic = 1,
Fire = 2,
Ice = 3,
Lightning = 4,
Light = 5,
Darkness = 6,
Explosive = 7
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ElementId
{
Physic = 0,
Magic = 1,
Fire = 2,
Ice = 3,
Lightning = 4,
Light = 5,
Darkness = 6,
Explosive = 7
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: d3e4e58ac7a97294b8f786fb9807f722
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: d3e4e58ac7a97294b8f786fb9807f722
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,37 +1,37 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemClass
{
Undefined,
Dagger,
Sword,
Axe,
Blunt,
Lance,
Wand,
Bow,
Light,
Heavy,
Ring,
Necklace,
Food,
Potion,
Scroll,
Bomb,
Pickaxe,
Claw,
Fang,
Skin,
Firearm,
Talisman,
Wood,
Ore,
Alloy,
Wings,
Shell,
Bone,
Leather,
Tail,
Gunpowder
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemClass
{
Undefined,
Dagger,
Sword,
Axe,
Blunt,
Lance,
Wand,
Bow,
Light,
Heavy,
Ring,
Necklace,
Food,
Potion,
Scroll,
Bomb,
Pickaxe,
Claw,
Fang,
Skin,
Firearm,
Talisman,
Wood,
Ore,
Alloy,
Wings,
Shell,
Bone,
Leather,
Tail,
Gunpowder
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: b7c544225668e5449917c12914e374c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: b7c544225668e5449917c12914e374c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,15 +1,15 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemMaterial
{
Unknown,
Wood,
Leather,
Metal,
Fruit,
Meat,
Liquid,
Soup,
Gold
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemMaterial
{
Unknown,
Wood,
Leather,
Metal,
Fruit,
Meat,
Liquid,
Soup,
Gold
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 4dd9d61b92101094b802a28c0c8ca697
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 4dd9d61b92101094b802a28c0c8ca697
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,12 +1,12 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemRarity
{
Legacy = -2,
Basic = -1,
Common = 0,
Rare = 1,
Epic = 2,
Legendary = 3
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemRarity
{
Legacy = -2,
Basic = -1,
Common = 0,
Rare = 1,
Epic = 2,
Legendary = 3
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 303a05ab03a515f4a81713e69dba20ed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 303a05ab03a515f4a81713e69dba20ed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,21 +1,21 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
/// <summary>
/// Item tags can be used for implementing custom logic (special cases).
/// Use constant integer values for enums to avoid data distortion when adding/removing new values.
/// </summary>
public enum ItemTag
{
Undefined = 0,
NotForSale = 1,
Quest = 2,
TwoHanded = 3,
Light = 4,
Heavy = 5,
Short = 6,
Long = 7,
Christmas = 8,
Farm = 9,
NoFragments = 10
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
/// <summary>
/// Item tags can be used for implementing custom logic (special cases).
/// Use constant integer values for enums to avoid data distortion when adding/removing new values.
/// </summary>
public enum ItemTag
{
Undefined = 0,
NotForSale = 1,
Quest = 2,
TwoHanded = 3,
Light = 4,
Heavy = 5,
Short = 6,
Long = 7,
Christmas = 8,
Farm = 9,
NoFragments = 10
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 195b18c85fc16e84690be89511476c51
timeCreated: 1508511989
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 195b18c85fc16e84690be89511476c51
timeCreated: 1508511989
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,32 +1,32 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
/// <summary>
/// Add new item groups here. Use constant integer values for enums to avoid data distortion when adding/removing new values.
/// </summary>
public enum ItemType
{
Undefined,
Currency,
Loot,
Material,
Supply,
Recipe,
Weapon,
Shield,
Armor,
Helmet,
Pauldrons,
Bracers,
Gloves,
Vest,
Belt,
Leggings,
Boots,
Jewelry,
Backpack,
Container,
Booster,
Coupon,
Fragment
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
/// <summary>
/// Add new item groups here. Use constant integer values for enums to avoid data distortion when adding/removing new values.
/// </summary>
public enum ItemType
{
Undefined,
Currency,
Loot,
Material,
Supply,
Recipe,
Weapon,
Shield,
Armor,
Helmet,
Pauldrons,
Bracers,
Gloves,
Vest,
Belt,
Leggings,
Boots,
Jewelry,
Backpack,
Container,
Booster,
Coupon,
Fragment
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 33c7fc0c41b95cb40a92474f536e960e
timeCreated: 1508494931
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 33c7fc0c41b95cb40a92474f536e960e
timeCreated: 1508494931
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,31 +1,31 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemModifier
{
None = 0,
Reinforced = 1, // Increase damage/resistance and STR req.
Refined = 2, // Increase damage/resistance and DEX req.
Sharpened = 3, // Critical damage up.
Lightweight = 4, // Reduce weight.
Poison = 5, // Add poison damage/resistance.
Bleeding = 6, // Add bleeding damage/resistance.
Spread = 7, // Reduced damage in a column.
Onslaught = 8, // Reduced damage in a line;
Shieldbreaker = 9, // Ignore shield.
Fire = 10, // Add fire damage/resistance.
Ice = 11, // Add ice damage/resistance.
Lightning = 12, // Add lightning damage/resistance.
Light = 13, // Add healing ability and halved holy damage/resistance.
Darkness = 14, // Add darkness damage/resistance.
Vampiric = 15, // Restore HP after each hit.
LevelDown = 16,
LevelUp = 17,
HealthUp = 18,
HealthRecovery = 19,
StaminaUp = 20,
StaminaRecovery = 21,
Speed = 22,
Accuracy = 23,
Reloading = 24
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
public enum ItemModifier
{
None = 0,
Reinforced = 1, // Increase damage/resistance and STR req.
Refined = 2, // Increase damage/resistance and DEX req.
Sharpened = 3, // Critical damage up.
Lightweight = 4, // Reduce weight.
Poison = 5, // Add poison damage/resistance.
Bleeding = 6, // Add bleeding damage/resistance.
Spread = 7, // Reduced damage in a column.
Onslaught = 8, // Reduced damage in a line;
Shieldbreaker = 9, // Ignore shield.
Fire = 10, // Add fire damage/resistance.
Ice = 11, // Add ice damage/resistance.
Lightning = 12, // Add lightning damage/resistance.
Light = 13, // Add healing ability and halved holy damage/resistance.
Darkness = 14, // Add darkness damage/resistance.
Vampiric = 15, // Restore HP after each hit.
LevelDown = 16,
LevelUp = 17,
HealthUp = 18,
HealthRecovery = 19,
StaminaUp = 20,
StaminaRecovery = 21,
Speed = 22,
Accuracy = 23,
Reloading = 24
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 017ab6f846822524494feeceee4b83b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 017ab6f846822524494feeceee4b83b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,54 +1,54 @@
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
/// <summary>
/// Add new item attributes here.
/// Use constant integer values for enums to avoid data distortion when adding/removing new values.
/// </summary>
public enum PropertyId // TODO: Set indexes.
{
Accuracy,
Ammo,
Antidote,
Bandage,
Blocking,
BlockingFatigue,
Capacity,
ChargeSpeed,
ChargeTimings,
Craft,
CriticalChance,
CriticalDamage,
CustomPrice,
Damage,
Duration,
Effect,
Exp,
Fatigue,
Gunpowder,
HealthRecovery,
HealthRestore,
HealthMax,
Immunity,
Magazine,
Materials,
Mechanism,
Radius,
Range,
Reloading,
Resistance,
ShopChance,
SkillUp,
Speed,
StaminaRecovery,
StaminaRestore,
StaminaMax,
Shock,
Contains,
DamageBonus,
Multishot,
Fragments,
DropChance,
ExpBonus,
GoldBonus
}
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Enums
{
/// <summary>
/// Add new item attributes here.
/// Use constant integer values for enums to avoid data distortion when adding/removing new values.
/// </summary>
public enum PropertyId // TODO: Set indexes.
{
Accuracy,
Ammo,
Antidote,
Bandage,
Blocking,
BlockingFatigue,
Capacity,
ChargeSpeed,
ChargeTimings,
Craft,
CriticalChance,
CriticalDamage,
CustomPrice,
Damage,
Duration,
Effect,
Exp,
Fatigue,
Gunpowder,
HealthRecovery,
HealthRestore,
HealthMax,
Immunity,
Magazine,
Materials,
Mechanism,
Radius,
Range,
Reloading,
Resistance,
ShopChance,
SkillUp,
Speed,
StaminaRecovery,
StaminaRestore,
StaminaMax,
Shock,
Contains,
DamageBonus,
Multishot,
Fragments,
DropChance,
ExpBonus,
GoldBonus
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 40e5239afe12eed45b619bd1bd5f1471
timeCreated: 1508511989
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 40e5239afe12eed45b619bd1bd5f1471
timeCreated: 1508511989
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +1,8 @@
fileFormatVersion: 2
guid: d9b405933d697694d92a73a417ddf114
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: d9b405933d697694d92a73a417ddf114
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,135 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.Common.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Helpers
{
public class CharacterInventorySetup
{
public static void Setup(Character character, List<Item> equipped, CharacterAppearance appearance)
{
if (!appearance.Underwear.IsEmpty())
{
character.Underwear = character.SpriteCollection.Armor.Single(i => i.Id == appearance.Underwear).Sprites;
}
character.UnderwearColor = appearance.UnderwearColor;
character.ShowHelmet = appearance.ShowHelmet;
appearance.Setup(character, initialize: false);
Setup(character, equipped);
}
public static void Setup(Character character, List<Item> equipped)
{
character.ResetEquipment();
character.HideEars = false;
character.CropHair = false;
foreach (var item in equipped)
{
try
{
var spriteCollection = character.SpriteCollection;
#if TAP_HEROES // TODO: Temp workaround.
if (item.Params.SpriteId.StartsWith("FantasyHeroes.Basic."))
{
spriteCollection = ItemCollection.Active.SpriteCollections.Single(i => i.Id == "FantasyHeroes");
}
else if (item.Params.SpriteId.StartsWith("FantasyHeroes.Goblin."))
{
spriteCollection = ItemCollection.Active.SpriteCollections.Single(i => i.Id == "GoblinHeroes");
}
else if (item.Params.SpriteId.StartsWith("UndeadHeroes."))
{
spriteCollection = ItemCollection.Active.SpriteCollections.Single(i => i.Id == "UndeadHeroes");
}
#endif
switch (item.Params.Type)
{
case ItemType.Weapon:
switch (item.Params.Class)
{
case ItemClass.Bow:
character.WeaponType = WeaponType.Bow;
character.CompositeWeapon = spriteCollection.Bow.FindSprites(item.Params.SpriteId);
break;
case ItemClass.Firearm:
character.WeaponType = WeaponType.Paired;
character.SecondaryWeapon = spriteCollection.Firearm1H.Union(spriteCollection.Firearm2H).FindSprites(item.Params.SpriteId).Single(i => i.name == "Side");
break;
default:
if (equipped.Any(i => i.IsFirearm))
{
character.WeaponType = WeaponType.Paired;
character.PrimaryWeapon = spriteCollection.MeleeWeapon1H.FindSprite(item.Params.SpriteId);
}
else
{
character.WeaponType = item.Params.Tags.Contains(ItemTag.TwoHanded) ? WeaponType.Melee2H : WeaponType.Melee1H;
character.PrimaryWeapon = (character.WeaponType == WeaponType.Melee1H ? spriteCollection.MeleeWeapon1H : spriteCollection.MeleeWeapon2H).FindSprite(item.Params.SpriteId);
}
break;
case ItemClass.Bomb:
character.WeaponType = WeaponType.Throwable;
character.PrimaryWeapon = spriteCollection.Throwable.FindSprite(item.Params.SpriteId);
break;
}
break;
case ItemType.Shield:
character.Shield = spriteCollection.Shield.FindSprites(item.Params.SpriteId);
character.WeaponType = WeaponType.Melee1H;
break;
case ItemType.Armor:
character.Armor = spriteCollection.Armor.FindSprites(item.Params.SpriteId);
break;
case ItemType.Helmet:
var entry = spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId);
character.Equip(entry, EquipmentPart.Helmet);
character.HideEars = !entry.Tags.Contains("ShowEars");
character.CropHair = !entry.Tags.Contains("FullHair");
break;
case ItemType.Vest:
character.Equip(spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId), EquipmentPart.Vest, Color.white);
break;
case ItemType.Bracers:
character.Equip(spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId), EquipmentPart.Bracers, Color.white);
break;
case ItemType.Leggings:
character.Equip(spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId), EquipmentPart.Leggings, Color.white);
break;
}
}
catch (Exception e)
{
Debug.LogErrorFormat("Unable to equip {0} ({1})", item.Params.SpriteId, e.Message);
}
}
foreach (var part in new[] { ItemType.Vest, ItemType.Bracers, ItemType.Leggings })
{
if (equipped.Any(i => i.Params.Type == part))
{
}
else if (character.Underwear.Any())
{
var entry = character.SpriteCollection.Armor.Single(i => i.Sprites.Contains(character.Underwear[0]));
character.Equip(entry, part.ToString().ToEnum<EquipmentPart>(), character.UnderwearColor);
}
}
character.Initialize();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.Common.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Helpers
{
public class CharacterInventorySetup
{
public static void Setup(Character character, List<Item> equipped, CharacterAppearance appearance)
{
if (!appearance.Underwear.IsEmpty())
{
character.Underwear = character.SpriteCollection.Armor.Single(i => i.Id == appearance.Underwear).Sprites;
}
character.UnderwearColor = appearance.UnderwearColor;
character.ShowHelmet = appearance.ShowHelmet;
appearance.Setup(character, initialize: false);
Setup(character, equipped);
}
public static void Setup(Character character, List<Item> equipped)
{
character.ResetEquipment();
character.HideEars = false;
character.CropHair = false;
foreach (var item in equipped)
{
try
{
var spriteCollection = character.SpriteCollection;
#if TAP_HEROES // TODO: Temp workaround.
if (item.Params.SpriteId.StartsWith("FantasyHeroes.Basic."))
{
spriteCollection = ItemCollection.Active.SpriteCollections.Single(i => i.Id == "FantasyHeroes");
}
else if (item.Params.SpriteId.StartsWith("FantasyHeroes.Goblin."))
{
spriteCollection = ItemCollection.Active.SpriteCollections.Single(i => i.Id == "GoblinHeroes");
}
else if (item.Params.SpriteId.StartsWith("UndeadHeroes."))
{
spriteCollection = ItemCollection.Active.SpriteCollections.Single(i => i.Id == "UndeadHeroes");
}
#endif
switch (item.Params.Type)
{
case ItemType.Weapon:
switch (item.Params.Class)
{
case ItemClass.Bow:
character.WeaponType = WeaponType.Bow;
character.CompositeWeapon = spriteCollection.Bow.FindSprites(item.Params.SpriteId);
break;
case ItemClass.Firearm:
character.WeaponType = WeaponType.Paired;
character.SecondaryWeapon = spriteCollection.Firearm1H.Union(spriteCollection.Firearm2H).FindSprites(item.Params.SpriteId).Single(i => i.name == "Side");
break;
default:
if (equipped.Any(i => i.IsFirearm))
{
character.WeaponType = WeaponType.Paired;
character.PrimaryWeapon = spriteCollection.MeleeWeapon1H.FindSprite(item.Params.SpriteId);
}
else
{
character.WeaponType = item.Params.Tags.Contains(ItemTag.TwoHanded) ? WeaponType.Melee2H : WeaponType.Melee1H;
character.PrimaryWeapon = (character.WeaponType == WeaponType.Melee1H ? spriteCollection.MeleeWeapon1H : spriteCollection.MeleeWeapon2H).FindSprite(item.Params.SpriteId);
}
break;
case ItemClass.Bomb:
character.WeaponType = WeaponType.Throwable;
character.PrimaryWeapon = spriteCollection.Throwable.FindSprite(item.Params.SpriteId);
break;
}
break;
case ItemType.Shield:
character.Shield = spriteCollection.Shield.FindSprites(item.Params.SpriteId);
character.WeaponType = WeaponType.Melee1H;
break;
case ItemType.Armor:
character.Armor = spriteCollection.Armor.FindSprites(item.Params.SpriteId);
break;
case ItemType.Helmet:
var entry = spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId);
character.Equip(entry, EquipmentPart.Helmet);
character.HideEars = !entry.Tags.Contains("ShowEars");
character.CropHair = !entry.Tags.Contains("FullHair");
break;
case ItemType.Vest:
character.Equip(spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId), EquipmentPart.Vest, Color.white);
break;
case ItemType.Bracers:
character.Equip(spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId), EquipmentPart.Bracers, Color.white);
break;
case ItemType.Leggings:
character.Equip(spriteCollection.Armor.Single(i => i.Id == item.Params.SpriteId), EquipmentPart.Leggings, Color.white);
break;
}
}
catch (Exception e)
{
Debug.LogErrorFormat("Unable to equip {0} ({1})", item.Params.SpriteId, e.Message);
}
}
foreach (var part in new[] { ItemType.Vest, ItemType.Bracers, ItemType.Leggings })
{
if (equipped.Any(i => i.Params.Type == part))
{
}
else if (character.Underwear.Any())
{
var entry = character.SpriteCollection.Armor.Single(i => i.Sprites.Contains(character.Underwear[0]));
character.Equip(entry, part.ToString().ToEnum<EquipmentPart>(), character.UnderwearColor);
}
}
character.Initialize();
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: d9432d5771f4c1f409fe5e1294778097
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: d9432d5771f4c1f409fe5e1294778097
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,36 +1,36 @@
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Helpers
{
public class SetupResolver : MonoBehaviour
{
public Character4D Character;
public Equipment Equipment;
public ItemWorkspace ItemWorkspace;
public List<Character4D> Characters;
public List<ItemCollection> ItemCollections;
/// <summary>
/// The main point of this method is to place a correct existing prefab on a scene.
/// </summary>
public void Awake()
{
if (Character != null)
{
Destroy(Character.gameObject);
Character = Instantiate(Characters.First(i => i != null));
Character.transform.position = new Vector3(0, 2.5f);
Character.SetDirection(Vector2.down);
if (Equipment) Equipment.Preview = Character.Front;
}
if (ItemWorkspace) ItemWorkspace.ItemCollection = ItemCollections.First(i => i != null);
}
}
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts.Helpers
{
public class SetupResolver : MonoBehaviour
{
public Character4D Character;
public Equipment Equipment;
public ItemWorkspace ItemWorkspace;
public List<Character4D> Characters;
public List<ItemCollection> ItemCollections;
/// <summary>
/// The main point of this method is to place a correct existing prefab on a scene.
/// </summary>
public void Awake()
{
if (Character != null)
{
Destroy(Character.gameObject);
Character = Instantiate(Characters.First(i => i != null));
Character.transform.position = new Vector3(0, 2.5f);
Character.SetDirection(Vector2.down);
if (Equipment) Equipment.Preview = Character.Front;
}
if (ItemWorkspace) ItemWorkspace.ItemCollection = ItemCollections.First(i => i != null);
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: bdd21f735b5f054448b0e96d62944905
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: bdd21f735b5f054448b0e96d62944905
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,334 +1,334 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
/// <summary>
/// High-level inventory interface.
/// </summary>
public class InventoryBase : ItemWorkspace
{
public Equipment Equipment;
public ScrollInventory PlayerInventory;
public ScrollInventory Materials;
public Button EquipButton;
public Button RemoveButton;
public Button CraftButton;
public Button LearnButton;
public Button UseButton;
public Button AssembleButton;
public AudioClip EquipSound;
public AudioClip CraftSound;
public AudioClip UseSound;
public AudioSource AudioSource;
public bool InitializeExample;
// These callbacks can be used outside;
public Action<Item> OnRefresh;
public Action<Item> OnEquip;
public Func<Item, bool> CanEquip = i => true;
public void Awake()
{
ItemCollection.Active = ItemCollection;
}
public void Start()
{
if (InitializeExample)
{
TestInitialize();
}
}
/// <summary>
/// Initialize owned items (just for example).
/// </summary>
public void TestInitialize()
{
var inventory = ItemCollection.Active.Items.Select(i => new Item(i.Id)).ToList(); // inventory.Clear();
var equipped = new List<Item>();
Initialize(ref inventory, ref equipped, 6, null);
}
public void Initialize(ref List<Item> inventory, ref List<Item> equipped, int bagSize, Action onRefresh)
{
RegisterCallbacks();
PlayerInventory.Initialize(ref inventory);
Equipment.SetBagSize(bagSize);
Equipment.Initialize(ref equipped);
Equipment.OnRefresh = onRefresh;
if (!Equipment.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void RegisterCallbacks()
{
InventoryItem.OnLeftClick = SelectItem;
InventoryItem.OnRightClick = InventoryItem.OnDoubleClick = QuickAction;
}
private void QuickAction(Item item)
{
SelectItem(item);
if (Equipment.Items.Contains(item))
{
Remove();
}
else if (CanEquipSelectedItem())
{
Equip();
}
}
public void SelectItem(Item item)
{
SelectedItem = item;
ItemInfo.Initialize(SelectedItem, SelectedItem.Params.Price);
Refresh();
}
public void Equip()
{
if (!CanEquip(SelectedItem)) return;
var equipped = SelectedItem.IsFirearm
? Equipment.Items.Where(i => i.IsFirearm).ToList()
: Equipment.Items.Where(i => i.Params.Type == SelectedItem.Params.Type && !i.IsFirearm).ToList();
if (equipped.Any())
{
AutoRemove(equipped, Equipment.Slots.Count(i => i.Supports(SelectedItem)));
}
if (SelectedItem.IsTwoHanded) AutoRemove(Equipment.Items.Where(i => i.IsShield).ToList());
if (SelectedItem.IsShield) AutoRemove(Equipment.Items.Where(i => i.IsWeapon && i.IsTwoHanded).ToList());
if (SelectedItem.IsFirearm) AutoRemove(Equipment.Items.Where(i => i.IsShield).ToList());
if (SelectedItem.IsFirearm) AutoRemove(Equipment.Items.Where(i => i.IsWeapon && i.IsTwoHanded).ToList());
if (SelectedItem.IsTwoHanded || SelectedItem.IsShield) AutoRemove(Equipment.Items.Where(i => i.IsWeapon && i.IsFirearm).ToList());
MoveItem(SelectedItem, PlayerInventory, Equipment);
AudioSource.PlayOneShot(EquipSound, SfxVolume);
OnEquip?.Invoke(SelectedItem);
}
public void Remove()
{
MoveItem(SelectedItem, Equipment, PlayerInventory);
SelectItem(SelectedItem);
AudioSource.PlayOneShot(EquipSound, SfxVolume);
}
public void Craft()
{
var materials = MaterialList;
if (CanCraft(materials))
{
materials.ForEach(i => PlayerInventory.Items.Single(j => j.Hash == i.Hash).Count -= i.Count);
PlayerInventory.Items.RemoveAll(i => i.Count == 0);
var itemId = SelectedItem.Params.FindProperty(PropertyId.Craft).Value;
var existed = PlayerInventory.Items.SingleOrDefault(i => i.Id == itemId && i.Modifier == null);
if (existed == null)
{
PlayerInventory.Items.Add(new Item(itemId));
}
else
{
existed.Count++;
}
PlayerInventory.Refresh(SelectedItem);
CraftButton.interactable = CanCraft(materials);
AudioSource.PlayOneShot(CraftSound, SfxVolume);
}
else
{
Debug.Log("No materials.");
}
}
public void Learn()
{
// Implement your logic here!
}
public void Use()
{
Use(UseSound);
}
public void Use(AudioClip sound)
{
if (SelectedItem.Count == 1)
{
PlayerInventory.Items.Remove(SelectedItem);
SelectedItem = PlayerInventory.Items.FirstOrDefault();
if (SelectedItem == null)
{
PlayerInventory.Refresh(null);
SelectedItem = Equipment.Items.FirstOrDefault();
if (SelectedItem != null)
{
Equipment.Refresh(SelectedItem);
}
}
else
{
PlayerInventory.Refresh(SelectedItem);
}
}
else
{
SelectedItem.Count--;
PlayerInventory.Refresh(SelectedItem);
}
Equipment.OnRefresh?.Invoke();
if (sound != null)
{
AudioSource.PlayOneShot(sound, SfxVolume);
}
}
public Item Assemble()
{
if (SelectedItem != null && SelectedItem.Params.Type == ItemType.Fragment && SelectedItem.Count >= SelectedItem.Params.FindProperty(PropertyId.Fragments).ValueInt)
{
SelectedItem.Count -= SelectedItem.Params.FindProperty(PropertyId.Fragments).ValueInt;
var crafted = new Item(SelectedItem.Params.FindProperty(PropertyId.Craft).Value);
var existed = PlayerInventory.Items.SingleOrDefault(i => i.Hash == crafted.Hash);
if (existed == null)
{
PlayerInventory.Items.Add(crafted);
}
else
{
existed.Count++;
}
if (SelectedItem.Count == 0)
{
PlayerInventory.Items.Remove(SelectedItem);
SelectedItem = crafted;
}
PlayerInventory.Refresh(SelectedItem);
return crafted;
}
return null;
}
public override void Refresh()
{
if (SelectedItem == null)
{
ItemInfo.Reset();
EquipButton.SetActive(false);
RemoveButton.SetActive(false);
}
else
{
var equipped = Equipment.Items.Contains(SelectedItem);
EquipButton.SetActive(!equipped && CanEquipSelectedItem());
RemoveButton.SetActive(equipped);
}
UseButton.SetActive(SelectedItem != null && CanUse());
AssembleButton.SetActive(SelectedItem != null && SelectedItem.Params.Type == ItemType.Fragment && SelectedItem.Count >= SelectedItem.Params.FindProperty(PropertyId.Fragments).ValueInt);
var receipt = SelectedItem != null && SelectedItem.Params.Type == ItemType.Recipe;
if (CraftButton != null) CraftButton.SetActive(false);
if (LearnButton != null) LearnButton.SetActive(false);
if (receipt)
{
if (LearnButton == null)
{
var materialSelected = !PlayerInventory.Items.Contains(SelectedItem) && !Equipment.Items.Contains(SelectedItem);
CraftButton.SetActive(true);
Materials.SetActive(materialSelected);
Equipment.Scheme.SetActive(!materialSelected);
var materials = MaterialList;
Materials.Initialize(ref materials);
}
else
{
LearnButton.SetActive(true);
}
}
OnRefresh?.Invoke(SelectedItem);
}
private List<Item> MaterialList => SelectedItem.Params.FindProperty(PropertyId.Materials).Value.Split(',').Select(i => i.Split(':')).Select(i => new Item(i[0], int.Parse(i[1]))).ToList();
private bool CanEquipSelectedItem()
{
return PlayerInventory.Items.Contains(SelectedItem) && Equipment.Slots.Any(i => i.Supports(SelectedItem));
}
private bool CanUse()
{
switch (SelectedItem.Params.Type)
{
case ItemType.Container:
case ItemType.Booster:
case ItemType.Coupon:
return true;
default:
return false;
}
}
private bool CanCraft(List<Item> materials)
{
return materials.All(i => PlayerInventory.Items.Any(j => j.Hash == i.Hash && j.Count >= i.Count));
}
/// <summary>
/// Automatically removes items if target slot is busy.
/// </summary>
private void AutoRemove(List<Item> items, int max = 1)
{
long sum = 0;
foreach (var p in items)
{
sum += p.Count;
}
if (sum == max)
{
MoveItemSilent(items.LastOrDefault(i => i.Id != SelectedItem.Id) ?? items.Last(), Equipment, PlayerInventory);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
/// <summary>
/// High-level inventory interface.
/// </summary>
public class InventoryBase : ItemWorkspace
{
public Equipment Equipment;
public ScrollInventory PlayerInventory;
public ScrollInventory Materials;
public Button EquipButton;
public Button RemoveButton;
public Button CraftButton;
public Button LearnButton;
public Button UseButton;
public Button AssembleButton;
public AudioClip EquipSound;
public AudioClip CraftSound;
public AudioClip UseSound;
public AudioSource AudioSource;
public bool InitializeExample;
// These callbacks can be used outside;
public Action<Item> OnRefresh;
public Action<Item> OnEquip;
public Func<Item, bool> CanEquip = i => true;
public void Awake()
{
ItemCollection.Active = ItemCollection;
}
public void Start()
{
if (InitializeExample)
{
TestInitialize();
}
}
/// <summary>
/// Initialize owned items (just for example).
/// </summary>
public void TestInitialize()
{
var inventory = ItemCollection.Active.Items.Select(i => new Item(i.Id)).ToList(); // inventory.Clear();
var equipped = new List<Item>();
Initialize(ref inventory, ref equipped, 6, null);
}
public void Initialize(ref List<Item> inventory, ref List<Item> equipped, int bagSize, Action onRefresh)
{
RegisterCallbacks();
PlayerInventory.Initialize(ref inventory);
Equipment.SetBagSize(bagSize);
Equipment.Initialize(ref equipped);
Equipment.OnRefresh = onRefresh;
if (!Equipment.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void RegisterCallbacks()
{
InventoryItem.OnLeftClick = SelectItem;
InventoryItem.OnRightClick = InventoryItem.OnDoubleClick = QuickAction;
}
private void QuickAction(Item item)
{
SelectItem(item);
if (Equipment.Items.Contains(item))
{
Remove();
}
else if (CanEquipSelectedItem())
{
Equip();
}
}
public void SelectItem(Item item)
{
SelectedItem = item;
ItemInfo.Initialize(SelectedItem, SelectedItem.Params.Price);
Refresh();
}
public void Equip()
{
if (!CanEquip(SelectedItem)) return;
var equipped = SelectedItem.IsFirearm
? Equipment.Items.Where(i => i.IsFirearm).ToList()
: Equipment.Items.Where(i => i.Params.Type == SelectedItem.Params.Type && !i.IsFirearm).ToList();
if (equipped.Any())
{
AutoRemove(equipped, Equipment.Slots.Count(i => i.Supports(SelectedItem)));
}
if (SelectedItem.IsTwoHanded) AutoRemove(Equipment.Items.Where(i => i.IsShield).ToList());
if (SelectedItem.IsShield) AutoRemove(Equipment.Items.Where(i => i.IsWeapon && i.IsTwoHanded).ToList());
if (SelectedItem.IsFirearm) AutoRemove(Equipment.Items.Where(i => i.IsShield).ToList());
if (SelectedItem.IsFirearm) AutoRemove(Equipment.Items.Where(i => i.IsWeapon && i.IsTwoHanded).ToList());
if (SelectedItem.IsTwoHanded || SelectedItem.IsShield) AutoRemove(Equipment.Items.Where(i => i.IsWeapon && i.IsFirearm).ToList());
MoveItem(SelectedItem, PlayerInventory, Equipment);
AudioSource.PlayOneShot(EquipSound, SfxVolume);
OnEquip?.Invoke(SelectedItem);
}
public void Remove()
{
MoveItem(SelectedItem, Equipment, PlayerInventory);
SelectItem(SelectedItem);
AudioSource.PlayOneShot(EquipSound, SfxVolume);
}
public void Craft()
{
var materials = MaterialList;
if (CanCraft(materials))
{
materials.ForEach(i => PlayerInventory.Items.Single(j => j.Hash == i.Hash).Count -= i.Count);
PlayerInventory.Items.RemoveAll(i => i.Count == 0);
var itemId = SelectedItem.Params.FindProperty(PropertyId.Craft).Value;
var existed = PlayerInventory.Items.SingleOrDefault(i => i.Id == itemId && i.Modifier == null);
if (existed == null)
{
PlayerInventory.Items.Add(new Item(itemId));
}
else
{
existed.Count++;
}
PlayerInventory.Refresh(SelectedItem);
CraftButton.interactable = CanCraft(materials);
AudioSource.PlayOneShot(CraftSound, SfxVolume);
}
else
{
Debug.Log("No materials.");
}
}
public void Learn()
{
// Implement your logic here!
}
public void Use()
{
Use(UseSound);
}
public void Use(AudioClip sound)
{
if (SelectedItem.Count == 1)
{
PlayerInventory.Items.Remove(SelectedItem);
SelectedItem = PlayerInventory.Items.FirstOrDefault();
if (SelectedItem == null)
{
PlayerInventory.Refresh(null);
SelectedItem = Equipment.Items.FirstOrDefault();
if (SelectedItem != null)
{
Equipment.Refresh(SelectedItem);
}
}
else
{
PlayerInventory.Refresh(SelectedItem);
}
}
else
{
SelectedItem.Count--;
PlayerInventory.Refresh(SelectedItem);
}
Equipment.OnRefresh?.Invoke();
if (sound != null)
{
AudioSource.PlayOneShot(sound, SfxVolume);
}
}
public Item Assemble()
{
if (SelectedItem != null && SelectedItem.Params.Type == ItemType.Fragment && SelectedItem.Count >= SelectedItem.Params.FindProperty(PropertyId.Fragments).ValueInt)
{
SelectedItem.Count -= SelectedItem.Params.FindProperty(PropertyId.Fragments).ValueInt;
var crafted = new Item(SelectedItem.Params.FindProperty(PropertyId.Craft).Value);
var existed = PlayerInventory.Items.SingleOrDefault(i => i.Hash == crafted.Hash);
if (existed == null)
{
PlayerInventory.Items.Add(crafted);
}
else
{
existed.Count++;
}
if (SelectedItem.Count == 0)
{
PlayerInventory.Items.Remove(SelectedItem);
SelectedItem = crafted;
}
PlayerInventory.Refresh(SelectedItem);
return crafted;
}
return null;
}
public override void Refresh()
{
if (SelectedItem == null)
{
ItemInfo.Reset();
EquipButton.SetActive(false);
RemoveButton.SetActive(false);
}
else
{
var equipped = Equipment.Items.Contains(SelectedItem);
EquipButton.SetActive(!equipped && CanEquipSelectedItem());
RemoveButton.SetActive(equipped);
}
UseButton.SetActive(SelectedItem != null && CanUse());
AssembleButton.SetActive(SelectedItem != null && SelectedItem.Params.Type == ItemType.Fragment && SelectedItem.Count >= SelectedItem.Params.FindProperty(PropertyId.Fragments).ValueInt);
var receipt = SelectedItem != null && SelectedItem.Params.Type == ItemType.Recipe;
if (CraftButton != null) CraftButton.SetActive(false);
if (LearnButton != null) LearnButton.SetActive(false);
if (receipt)
{
if (LearnButton == null)
{
var materialSelected = !PlayerInventory.Items.Contains(SelectedItem) && !Equipment.Items.Contains(SelectedItem);
CraftButton.SetActive(true);
Materials.SetActive(materialSelected);
Equipment.Scheme.SetActive(!materialSelected);
var materials = MaterialList;
Materials.Initialize(ref materials);
}
else
{
LearnButton.SetActive(true);
}
}
OnRefresh?.Invoke(SelectedItem);
}
private List<Item> MaterialList => SelectedItem.Params.FindProperty(PropertyId.Materials).Value.Split(',').Select(i => i.Split(':')).Select(i => new Item(i[0], int.Parse(i[1]))).ToList();
private bool CanEquipSelectedItem()
{
return PlayerInventory.Items.Contains(SelectedItem) && Equipment.Slots.Any(i => i.Supports(SelectedItem));
}
private bool CanUse()
{
switch (SelectedItem.Params.Type)
{
case ItemType.Container:
case ItemType.Booster:
case ItemType.Coupon:
return true;
default:
return false;
}
}
private bool CanCraft(List<Item> materials)
{
return materials.All(i => PlayerInventory.Items.Any(j => j.Hash == i.Hash && j.Count >= i.Count));
}
/// <summary>
/// Automatically removes items if target slot is busy.
/// </summary>
private void AutoRemove(List<Item> items, int max = 1)
{
long sum = 0;
foreach (var p in items)
{
sum += p.Count;
}
if (sum == max)
{
MoveItemSilent(items.LastOrDefault(i => i.Id != SelectedItem.Id) ?? items.Last(), Equipment, PlayerInventory);
}
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: 19c811bc87eaeaa40b393fb28d6a70cb
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 19c811bc87eaeaa40b393fb28d6a70cb
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,178 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Collections;
using Assets.HeroEditor4D.Common.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
[CreateAssetMenu(fileName = "ItemCollection", menuName = "HeroEditor4D/ItemCollection")]
public class ItemCollection : ScriptableObject
{
[Header("Main")]
public List<SpriteCollection> SpriteCollections = new();
public List<IconCollection> IconCollections = new();
public List<ItemParams> Items = new();
[Header("Extra")]
public Sprite BackgroundBlue;
public Sprite BackgroundBrown;
public Sprite BackgroundGreen;
public Sprite BackgroundGrey;
public Sprite BackgroundPurple;
public Sprite BackgroundRed;
public static ItemCollection Active;
private Dictionary<string, ItemSprite> _itemSprites;
private Dictionary<string, ItemIcon> _itemIcons;
public Func<Item, ItemParams> GetItemParamsOverride;
public void OnEnable()
{
Items.ForEach(i => i.Properties.ForEach(p => p.ParseValue()));
}
public ItemParams GetItemParams(Item item)
{
if (GetItemParamsOverride != null) return GetItemParamsOverride(item);
var itemParams = Items.SingleOrDefault(i => i.Id == item.Id);
if (itemParams == null)
{
throw new Exception($"Item params not found: {item.Id}");
}
return itemParams;
}
public ItemSprite GetItemSprite(Item item)
{
_itemSprites ??= CacheSprites();
var itemParams = GetItemParams(item);
if (itemParams.SpriteId == null) return null;
if (_itemSprites.ContainsKey(itemParams.SpriteId))
{
return _itemSprites[itemParams.SpriteId];
}
Debug.LogWarning($"Sprite not found: {itemParams.SpriteId}");
return null;
}
public ItemIcon GetItemIcon(Item item)
{
_itemIcons ??= CacheIcons();
var itemParams = GetItemParams(item);
if (itemParams.IconId == null) return null;
if (_itemIcons.ContainsKey(itemParams.IconId))
{
return _itemIcons[itemParams.IconId];
}
Debug.LogWarning($"Icon not found: {itemParams.IconId}");
return null;
}
/// <summary>
/// Can be used to find sprites directly, with no existing items needed.
/// </summary>
public Sprite FindSprite(string spriteId)
{
_itemSprites ??= CacheSprites();
if (spriteId != null && _itemSprites.ContainsKey(spriteId))
{
return _itemSprites[spriteId].Sprite;
}
Debug.LogWarning($"Sprite not found: {spriteId}");
return null;
}
/// <summary>
/// Can be used to find icons directly, with no existing items needed.
/// </summary>
public Sprite FindIcon(string iconId)
{
_itemIcons ??= CacheIcons();
if (iconId != null && _itemIcons.ContainsKey(iconId))
{
return _itemIcons[iconId].Sprite;
}
Debug.LogWarning($"Icon not found: {iconId}");
return null;
}
public Func<Item, Sprite> GetBackgroundCustom;
public Sprite GetBackground(Item item)
{
if (GetBackgroundCustom != null) return GetBackgroundCustom(item) ?? BackgroundBrown;
switch (item.Params.Rarity)
{
case ItemRarity.Legacy: return BackgroundGrey;
case ItemRarity.Basic: return BackgroundGrey;
case ItemRarity.Common: return BackgroundBrown;
case ItemRarity.Rare: return BackgroundRed;
case ItemRarity.Epic: return BackgroundBlue;
case ItemRarity.Legendary: return BackgroundPurple;
default: throw new NotImplementedException();
}
}
public void Reset()
{
_itemSprites = null;
_itemIcons = null;
}
private Dictionary<string, ItemSprite> CacheSprites()
{
var dict = new Dictionary<string, ItemSprite>();
foreach (var sprite in SpriteCollections.SelectMany(i => i.GetAllSprites()))
{
if (!dict.ContainsKey(sprite.Id))
{
dict.Add(sprite.Id, sprite);
}
}
return dict;
}
private Dictionary<string, ItemIcon> CacheIcons()
{
var dict = new Dictionary<string, ItemIcon>();
foreach (var icon in IconCollections.SelectMany(i => i.Icons))
{
if (!dict.ContainsKey(icon.Id))
{
dict.Add(icon.Id, icon);
}
}
return dict;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Collections;
using Assets.HeroEditor4D.Common.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using UnityEngine;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
[CreateAssetMenu(fileName = "ItemCollection", menuName = "HeroEditor4D/ItemCollection")]
public class ItemCollection : ScriptableObject
{
[Header("Main")]
public List<SpriteCollection> SpriteCollections = new();
public List<IconCollection> IconCollections = new();
public List<ItemParams> Items = new();
[Header("Extra")]
public Sprite BackgroundBlue;
public Sprite BackgroundBrown;
public Sprite BackgroundGreen;
public Sprite BackgroundGrey;
public Sprite BackgroundPurple;
public Sprite BackgroundRed;
public static ItemCollection Active;
private Dictionary<string, ItemSprite> _itemSprites;
private Dictionary<string, ItemIcon> _itemIcons;
public Func<Item, ItemParams> GetItemParamsOverride;
public void OnEnable()
{
Items.ForEach(i => i.Properties.ForEach(p => p.ParseValue()));
}
public ItemParams GetItemParams(Item item)
{
if (GetItemParamsOverride != null) return GetItemParamsOverride(item);
var itemParams = Items.SingleOrDefault(i => i.Id == item.Id);
if (itemParams == null)
{
throw new Exception($"Item params not found: {item.Id}");
}
return itemParams;
}
public ItemSprite GetItemSprite(Item item)
{
_itemSprites ??= CacheSprites();
var itemParams = GetItemParams(item);
if (itemParams.SpriteId == null) return null;
if (_itemSprites.ContainsKey(itemParams.SpriteId))
{
return _itemSprites[itemParams.SpriteId];
}
Debug.LogWarning($"Sprite not found: {itemParams.SpriteId}");
return null;
}
public ItemIcon GetItemIcon(Item item)
{
_itemIcons ??= CacheIcons();
var itemParams = GetItemParams(item);
if (itemParams.IconId == null) return null;
if (_itemIcons.ContainsKey(itemParams.IconId))
{
return _itemIcons[itemParams.IconId];
}
Debug.LogWarning($"Icon not found: {itemParams.IconId}");
return null;
}
/// <summary>
/// Can be used to find sprites directly, with no existing items needed.
/// </summary>
public Sprite FindSprite(string spriteId)
{
_itemSprites ??= CacheSprites();
if (spriteId != null && _itemSprites.ContainsKey(spriteId))
{
return _itemSprites[spriteId].Sprite;
}
Debug.LogWarning($"Sprite not found: {spriteId}");
return null;
}
/// <summary>
/// Can be used to find icons directly, with no existing items needed.
/// </summary>
public Sprite FindIcon(string iconId)
{
_itemIcons ??= CacheIcons();
if (iconId != null && _itemIcons.ContainsKey(iconId))
{
return _itemIcons[iconId].Sprite;
}
Debug.LogWarning($"Icon not found: {iconId}");
return null;
}
public Func<Item, Sprite> GetBackgroundCustom;
public Sprite GetBackground(Item item)
{
if (GetBackgroundCustom != null) return GetBackgroundCustom(item) ?? BackgroundBrown;
switch (item.Params.Rarity)
{
case ItemRarity.Legacy: return BackgroundGrey;
case ItemRarity.Basic: return BackgroundGrey;
case ItemRarity.Common: return BackgroundBrown;
case ItemRarity.Rare: return BackgroundRed;
case ItemRarity.Epic: return BackgroundBlue;
case ItemRarity.Legendary: return BackgroundPurple;
default: throw new NotImplementedException();
}
}
public void Reset()
{
_itemSprites = null;
_itemIcons = null;
}
private Dictionary<string, ItemSprite> CacheSprites()
{
var dict = new Dictionary<string, ItemSprite>();
foreach (var sprite in SpriteCollections.SelectMany(i => i.GetAllSprites()))
{
if (!dict.ContainsKey(sprite.Id))
{
dict.Add(sprite.Id, sprite);
}
}
return dict;
}
private Dictionary<string, ItemIcon> CacheIcons()
{
var dict = new Dictionary<string, ItemIcon>();
foreach (var icon in IconCollections.SelectMany(i => i.Icons))
{
if (!dict.ContainsKey(icon.Id))
{
dict.Add(icon.Id, icon);
}
}
return dict;
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: aa5c5884bb17ba64481f623ebc4accaa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: aa5c5884bb17ba64481f623ebc4accaa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,307 +1,307 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
/// <summary>
/// High-level shop interface.
/// </summary>
public class ShopBase : ItemWorkspace
{
public ScrollInventory TraderInventory;
public ScrollInventory PlayerInventory;
public InputField AmountInput;
public Button BuyButton;
public Button SellButton;
public AudioSource AudioSource;
public AudioClip TradeSound;
public AudioClip NoMoney;
public Character Dummy;
public bool ExampleInitialize;
public string CurrencyId = "Gold";
public int Amount;
// These callbacks can be used outside;
public Action<Item> OnRefresh;
public Action<Item> OnBuy;
public Action<Item> OnSell;
public void Awake()
{
// You must to set an active collection (as there may be several different collections in Resources).
ItemCollection.Active = ItemCollection;
}
public void Start()
{
if (ExampleInitialize)
{
TestInitialize();
}
}
public virtual bool CanBuy(Item item) // Override this function to fit your needs!
{
return true;
}
public virtual bool CanSell(Item item) // Override this function to fit your needs!
{
return true;
}
public virtual int GetPrice(Item item) // Override this function to fit your needs!
{
var trader = TraderInventory.Items.Contains(item);
var price = item.Params.Price * Amount;
if (trader)
{
price *= GetTraderMarkup(item);
}
return price;
}
public static int GetTraderMarkup(Item item) // Override this function to fit your needs!
{
if (item.Params.Rarity > ItemRarity.Common) return 2;
switch (item.Params.Type)
{
case ItemType.Weapon:
case ItemType.Armor:
case ItemType.Helmet:
case ItemType.Shield:
case ItemType.Backpack: return 3;
default: return 2;
}
}
public void RegisterCallbacks()
{
InventoryItem.OnLeftClick = SelectItem;
InventoryItem.OnRightClick = InventoryItem.OnDoubleClick = item => { SelectItem(item); if (TraderInventory.Items.Contains(item)) Buy(); else Sell(); };
}
/// <summary>
/// Initialize owned items and trader items (just for example).
/// </summary>
public void TestInitialize()
{
var inventory = new List<Item> { new Item(CurrencyId, 10000) };
var shop = ItemCollection.Active.Items.Select(i => new Item(i.Id, 2)).ToList();
shop.Single(i => i.Id == CurrencyId).Count = 99999;
RegisterCallbacks();
TraderInventory.Initialize(ref shop);
PlayerInventory.Initialize(ref inventory);
if (!TraderInventory.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void Initialize(ref List<Item> traderItems, ref List<Item> playerItems)
{
RegisterCallbacks();
TraderInventory.Initialize(ref traderItems);
PlayerInventory.Initialize(ref playerItems);
if (!TraderInventory.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void SelectItem(Item item)
{
SelectedItem = item;
SetAmount(1);
ItemInfo.Initialize(SelectedItem, GetPrice(SelectedItem), TraderInventory.Items.Contains(item));
Refresh();
}
public void Buy()
{
if (!BuyButton.gameObject.activeSelf || !BuyButton.interactable || !CanBuy(SelectedItem)) return;
var item = SelectedItem;
var price = GetPrice(item);
if (GetCurrency(PlayerInventory, CurrencyId) < price)
{
#if TAP_HEROES
TapHeroes.Scripts.Interface.Popup.Instance.ShowMessage(SimpleLocalization.LocalizationManager.Localize("Common.NoFunds", "[" + TapHeroes.Scripts.Extensions.GetLocalizedName(new Item(CurrencyId).Params) + "]"), CurrencyId, NoMoney);
#else
Debug.LogWarning("You don't have enough gold!");
AudioSource.PlayOneShot(NoMoney, SfxVolume);
#endif
return;
}
OnBuy?.Invoke(item);
AddMoney(PlayerInventory, -price, CurrencyId);
AddMoney(TraderInventory, price, CurrencyId);
MoveItem(item, TraderInventory, PlayerInventory, Amount, currencyId: CurrencyId);
AudioSource.PlayOneShot(TradeSound, SfxVolume);
#if TAP_HEROES
TapHeroes.Scripts.Interface.Tutorial.Instance.OnBuyItem(item.Id); // TODO: Create OnBuyCallback;
#endif
}
public void Sell()
{
if (!SellButton.gameObject.activeSelf || !SellButton.interactable || !CanSell(SelectedItem)) return;
var price = GetPrice(SelectedItem);
if (GetCurrency(TraderInventory, CurrencyId) < price)
{
#if TAP_HEROES
TapHeroes.Scripts.Interface.Popup.Instance.ShowMessage(SimpleLocalization.LocalizationManager.Localize("Common.NoFunds", "[" + TapHeroes.Scripts.Extensions.GetLocalizedName(new Item(CurrencyId).Params) + "]"), CurrencyId, NoMoney);
#else
Debug.LogWarning("Trader doesn't have enough gold!");
AudioSource.PlayOneShot(NoMoney, SfxVolume);
#endif
return;
}
OnSell?.Invoke(SelectedItem);
AddMoney(PlayerInventory, price, CurrencyId);
AddMoney(TraderInventory, -price, CurrencyId);
MoveItem(SelectedItem, PlayerInventory, TraderInventory, Amount, currencyId: CurrencyId);
AudioSource.PlayOneShot(TradeSound, SfxVolume);
}
public override void Refresh()
{
if (SelectedItem == null)
{
ItemInfo.Reset();
BuyButton.SetActive(false);
SellButton.SetActive(false);
}
else
{
if (TraderInventory.Items.Contains(SelectedItem))
{
InitBuy();
}
else if (PlayerInventory.Items.Contains(SelectedItem))
{
InitSell();
}
else if (TraderInventory.Items.Any(i => i.Hash == SelectedItem.Hash))
{
InitBuy();
}
else if (PlayerInventory.Items.Any(i => i.Hash == SelectedItem.Hash))
{
InitSell();
}
}
OnRefresh?.Invoke(SelectedItem);
}
public void SetMinAmount()
{
SetAmount(1);
}
public void IncAmount(int value)
{
SetAmount(Amount + value);
}
public void SetMaxAmount()
{
SetAmount(SelectedItem.Count);
}
public void OnAmountChanged(string value)
{
if (value.IsEmpty()) return;
SetAmount(int.Parse(value));
}
public void OnAmountEndEdit(string value)
{
if (value.IsEmpty())
{
SetAmount(1);
}
}
private void SetAmount(int amount)
{
Amount = Mathf.Max(1, Mathf.Min(SelectedItem.Count, amount));
AmountInput?.SetTextWithoutNotify(Amount.ToString());
ItemInfo.UpdatePrice(SelectedItem, GetPrice(SelectedItem), TraderInventory.Items.Contains(SelectedItem));
}
private void InitBuy()
{
BuyButton.SetActive(SelectedItem.Params.Type != ItemType.Currency && SelectedItem.Count > 0 && !SelectedItem.Params.Tags.Contains(ItemTag.NotForSale) && !SelectedItem.Params.Tags.Contains(ItemTag.Quest) && CanBuy(SelectedItem));
SellButton.SetActive(false);
//BuyButton.interactable = GetCurrency(Bag, CurrencyId) >= SelectedItem.Params.Price;
}
private void InitSell()
{
BuyButton.SetActive(false);
SellButton.SetActive(SelectedItem.Count > 0 && !SelectedItem.Params.Tags.Contains(ItemTag.NotForSale) && !SelectedItem.Params.Tags.Contains(ItemTag.Quest) && SelectedItem.Id != CurrencyId && CanSell(SelectedItem));
//SellButton.interactable = GetCurrency(Trader, CurrencyId) >= SelectedItem.Params.Price;
}
public static long GetCurrency(ItemContainer bag, string currencyId)
{
var currency = bag.Items.SingleOrDefault(i => i.Id == currencyId);
return currency?.Count ?? 0;
}
private static void AddMoney(ItemContainer inventory, int value, string currencyId)
{
var currency = inventory.Items.SingleOrDefault(i => i.Id == currencyId);
if (currency == null)
{
inventory.Items.Insert(0, new Item(currencyId, value));
}
else
{
currency.Count += value;
if (currency.Count == 0)
{
inventory.Items.Remove(currency);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
/// <summary>
/// High-level shop interface.
/// </summary>
public class ShopBase : ItemWorkspace
{
public ScrollInventory TraderInventory;
public ScrollInventory PlayerInventory;
public InputField AmountInput;
public Button BuyButton;
public Button SellButton;
public AudioSource AudioSource;
public AudioClip TradeSound;
public AudioClip NoMoney;
public Character Dummy;
public bool ExampleInitialize;
public string CurrencyId = "Gold";
public int Amount;
// These callbacks can be used outside;
public Action<Item> OnRefresh;
public Action<Item> OnBuy;
public Action<Item> OnSell;
public void Awake()
{
// You must to set an active collection (as there may be several different collections in Resources).
ItemCollection.Active = ItemCollection;
}
public void Start()
{
if (ExampleInitialize)
{
TestInitialize();
}
}
public virtual bool CanBuy(Item item) // Override this function to fit your needs!
{
return true;
}
public virtual bool CanSell(Item item) // Override this function to fit your needs!
{
return true;
}
public virtual int GetPrice(Item item) // Override this function to fit your needs!
{
var trader = TraderInventory.Items.Contains(item);
var price = item.Params.Price * Amount;
if (trader)
{
price *= GetTraderMarkup(item);
}
return price;
}
public static int GetTraderMarkup(Item item) // Override this function to fit your needs!
{
if (item.Params.Rarity > ItemRarity.Common) return 2;
switch (item.Params.Type)
{
case ItemType.Weapon:
case ItemType.Armor:
case ItemType.Helmet:
case ItemType.Shield:
case ItemType.Backpack: return 3;
default: return 2;
}
}
public void RegisterCallbacks()
{
InventoryItem.OnLeftClick = SelectItem;
InventoryItem.OnRightClick = InventoryItem.OnDoubleClick = item => { SelectItem(item); if (TraderInventory.Items.Contains(item)) Buy(); else Sell(); };
}
/// <summary>
/// Initialize owned items and trader items (just for example).
/// </summary>
public void TestInitialize()
{
var inventory = new List<Item> { new Item(CurrencyId, 10000) };
var shop = ItemCollection.Active.Items.Select(i => new Item(i.Id, 2)).ToList();
shop.Single(i => i.Id == CurrencyId).Count = 99999;
RegisterCallbacks();
TraderInventory.Initialize(ref shop);
PlayerInventory.Initialize(ref inventory);
if (!TraderInventory.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void Initialize(ref List<Item> traderItems, ref List<Item> playerItems)
{
RegisterCallbacks();
TraderInventory.Initialize(ref traderItems);
PlayerInventory.Initialize(ref playerItems);
if (!TraderInventory.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void SelectItem(Item item)
{
SelectedItem = item;
SetAmount(1);
ItemInfo.Initialize(SelectedItem, GetPrice(SelectedItem), TraderInventory.Items.Contains(item));
Refresh();
}
public void Buy()
{
if (!BuyButton.gameObject.activeSelf || !BuyButton.interactable || !CanBuy(SelectedItem)) return;
var item = SelectedItem;
var price = GetPrice(item);
if (GetCurrency(PlayerInventory, CurrencyId) < price)
{
#if TAP_HEROES
TapHeroes.Scripts.Interface.Popup.Instance.ShowMessage(SimpleLocalization.LocalizationManager.Localize("Common.NoFunds", "[" + TapHeroes.Scripts.Extensions.GetLocalizedName(new Item(CurrencyId).Params) + "]"), CurrencyId, NoMoney);
#else
Debug.LogWarning("You don't have enough gold!");
AudioSource.PlayOneShot(NoMoney, SfxVolume);
#endif
return;
}
OnBuy?.Invoke(item);
AddMoney(PlayerInventory, -price, CurrencyId);
AddMoney(TraderInventory, price, CurrencyId);
MoveItem(item, TraderInventory, PlayerInventory, Amount, currencyId: CurrencyId);
AudioSource.PlayOneShot(TradeSound, SfxVolume);
#if TAP_HEROES
TapHeroes.Scripts.Interface.Tutorial.Instance.OnBuyItem(item.Id); // TODO: Create OnBuyCallback;
#endif
}
public void Sell()
{
if (!SellButton.gameObject.activeSelf || !SellButton.interactable || !CanSell(SelectedItem)) return;
var price = GetPrice(SelectedItem);
if (GetCurrency(TraderInventory, CurrencyId) < price)
{
#if TAP_HEROES
TapHeroes.Scripts.Interface.Popup.Instance.ShowMessage(SimpleLocalization.LocalizationManager.Localize("Common.NoFunds", "[" + TapHeroes.Scripts.Extensions.GetLocalizedName(new Item(CurrencyId).Params) + "]"), CurrencyId, NoMoney);
#else
Debug.LogWarning("Trader doesn't have enough gold!");
AudioSource.PlayOneShot(NoMoney, SfxVolume);
#endif
return;
}
OnSell?.Invoke(SelectedItem);
AddMoney(PlayerInventory, price, CurrencyId);
AddMoney(TraderInventory, -price, CurrencyId);
MoveItem(SelectedItem, PlayerInventory, TraderInventory, Amount, currencyId: CurrencyId);
AudioSource.PlayOneShot(TradeSound, SfxVolume);
}
public override void Refresh()
{
if (SelectedItem == null)
{
ItemInfo.Reset();
BuyButton.SetActive(false);
SellButton.SetActive(false);
}
else
{
if (TraderInventory.Items.Contains(SelectedItem))
{
InitBuy();
}
else if (PlayerInventory.Items.Contains(SelectedItem))
{
InitSell();
}
else if (TraderInventory.Items.Any(i => i.Hash == SelectedItem.Hash))
{
InitBuy();
}
else if (PlayerInventory.Items.Any(i => i.Hash == SelectedItem.Hash))
{
InitSell();
}
}
OnRefresh?.Invoke(SelectedItem);
}
public void SetMinAmount()
{
SetAmount(1);
}
public void IncAmount(int value)
{
SetAmount(Amount + value);
}
public void SetMaxAmount()
{
SetAmount(SelectedItem.Count);
}
public void OnAmountChanged(string value)
{
if (value.IsEmpty()) return;
SetAmount(int.Parse(value));
}
public void OnAmountEndEdit(string value)
{
if (value.IsEmpty())
{
SetAmount(1);
}
}
private void SetAmount(int amount)
{
Amount = Mathf.Max(1, Mathf.Min(SelectedItem.Count, amount));
AmountInput?.SetTextWithoutNotify(Amount.ToString());
ItemInfo.UpdatePrice(SelectedItem, GetPrice(SelectedItem), TraderInventory.Items.Contains(SelectedItem));
}
private void InitBuy()
{
BuyButton.SetActive(SelectedItem.Params.Type != ItemType.Currency && SelectedItem.Count > 0 && !SelectedItem.Params.Tags.Contains(ItemTag.NotForSale) && !SelectedItem.Params.Tags.Contains(ItemTag.Quest) && CanBuy(SelectedItem));
SellButton.SetActive(false);
//BuyButton.interactable = GetCurrency(Bag, CurrencyId) >= SelectedItem.Params.Price;
}
private void InitSell()
{
BuyButton.SetActive(false);
SellButton.SetActive(SelectedItem.Count > 0 && !SelectedItem.Params.Tags.Contains(ItemTag.NotForSale) && !SelectedItem.Params.Tags.Contains(ItemTag.Quest) && SelectedItem.Id != CurrencyId && CanSell(SelectedItem));
//SellButton.interactable = GetCurrency(Trader, CurrencyId) >= SelectedItem.Params.Price;
}
public static long GetCurrency(ItemContainer bag, string currencyId)
{
var currency = bag.Items.SingleOrDefault(i => i.Id == currencyId);
return currency?.Count ?? 0;
}
private static void AddMoney(ItemContainer inventory, int value, string currencyId)
{
var currency = inventory.Items.SingleOrDefault(i => i.Id == currencyId);
if (currency == null)
{
inventory.Items.Insert(0, new Item(currencyId, value));
}
else
{
currency.Count += value;
if (currency.Count == 0)
{
inventory.Items.Remove(currency);
}
}
}
}
}

View File

@@ -1,12 +1,12 @@
fileFormatVersion: 2
guid: bc3a4dc52bc9967418be3e1e56056abc
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: bc3a4dc52bc9967418be3e1e56056abc
timeCreated: 1508494765
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,197 +1,197 @@
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
/// <summary>
/// High-level inventory interface.
/// </summary>
public class WarehouseBase : ItemWorkspace
{
public ScrollInventory WarehouseInventory;
public ScrollInventory PlayerInventory;
public InputField AmountInput;
public Button PutButton;
public Button TakeButton;
public AudioClip MoveSound;
public AudioSource AudioSource;
public bool ExampleInitialize;
public string CurrencyId = "Gold";
public int Amount;
public void Awake()
{
// You must to set an active collection (as there may be several different collections in Resources).
ItemCollection.Active = ItemCollection;
}
public void Start()
{
if (ExampleInitialize)
{
TestInitialize();
}
}
/// <summary>
/// Initialize owned items and trader items (just for example).
/// </summary>
public void TestInitialize()
{
var warehouse = new List<Item>();
var inventory = ItemCollection.Active.Items.Select(i => new Item(i.Id, 2)).ToList();
RegisterCallbacks();
WarehouseInventory.Initialize(ref warehouse);
PlayerInventory.Initialize(ref inventory);
if (!WarehouseInventory.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void Initialize(ref List<Item> playerItems, ref List<Item> storageItems)
{
RegisterCallbacks();
PlayerInventory.Initialize(ref playerItems);
WarehouseInventory.Initialize(ref storageItems);
if (!PlayerInventory.SelectAny() && !WarehouseInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void RegisterCallbacks()
{
InventoryItem.OnLeftClick = SelectItem;
InventoryItem.OnRightClick = OnDoubleClick;
}
private void OnDoubleClick(Item item)
{
SelectItem(item);
if (PlayerInventory.Items.Contains(item))
{
Take();
}
else if (CanMoveSelectedItem())
{
Put();
}
}
public void SelectItem(Item item)
{
SelectedItem = item;
SetAmount(1);
ItemInfo.Initialize(SelectedItem, SelectedItem.Params.Price * Amount);
Refresh();
}
public void Put()
{
if (!CanMoveSelectedItem()) return;
MoveItem(SelectedItem, PlayerInventory, WarehouseInventory, Amount);
SelectItem(SelectedItem);
AudioSource.PlayOneShot(MoveSound, SfxVolume);
}
public void Take()
{
if (!CanMoveSelectedItem()) return;
MoveItem(SelectedItem, WarehouseInventory, PlayerInventory, Amount);
SelectItem(SelectedItem);
AudioSource.PlayOneShot(MoveSound, SfxVolume);
}
public override void Refresh()
{
if (SelectedItem == null)
{
ItemInfo.Reset();
PutButton.SetActive(false);
TakeButton.SetActive(false);
}
else
{
var stored = WarehouseInventory.Items.Contains(SelectedItem);
PutButton.SetActive(!stored && CanMoveSelectedItem());
TakeButton.SetActive(stored && CanMoveSelectedItem());
}
}
public void SetMinAmount()
{
SetAmount(1);
}
public void IncAmount(int value)
{
SetAmount(Amount + value);
}
public void SetMaxAmount()
{
SetAmount(SelectedItem.Count);
}
public void OnAmountChanged(string value)
{
if (value.IsEmpty()) return;
SetAmount(int.Parse(value));
}
public void OnAmountEndEdit(string value)
{
if (value.IsEmpty())
{
SetAmount(1);
}
}
public void Drop()
{
foreach (var item in PlayerInventory.Items.ToList())
{
if (item.Params.Type != ItemType.Currency && !item.Params.Tags.Contains(ItemTag.Quest))
{
#if TAP_HEROES
if (item.Params.Class == ItemClass.Gunpowder) continue;
#endif
MoveItem(item, PlayerInventory, WarehouseInventory, item.Count);
}
}
AudioSource.PlayOneShot(MoveSound, SfxVolume);
}
private void SetAmount(int amount)
{
Amount = Mathf.Max(1, Mathf.Min(SelectedItem.Count, amount));
AmountInput?.SetTextWithoutNotify(Amount.ToString());
ItemInfo.UpdatePrice(SelectedItem, SelectedItem.Params.Price * Amount, false);
}
protected virtual bool CanMoveSelectedItem()
{
return true;
}
}
using System.Collections.Generic;
using System.Linq;
using Assets.HeroEditor4D.Common.Scripts.Common;
using Assets.HeroEditor4D.InventorySystem.Scripts.Data;
using Assets.HeroEditor4D.InventorySystem.Scripts.Enums;
using Assets.HeroEditor4D.InventorySystem.Scripts.Elements;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.HeroEditor4D.InventorySystem.Scripts
{
/// <summary>
/// High-level inventory interface.
/// </summary>
public class WarehouseBase : ItemWorkspace
{
public ScrollInventory WarehouseInventory;
public ScrollInventory PlayerInventory;
public InputField AmountInput;
public Button PutButton;
public Button TakeButton;
public AudioClip MoveSound;
public AudioSource AudioSource;
public bool ExampleInitialize;
public string CurrencyId = "Gold";
public int Amount;
public void Awake()
{
// You must to set an active collection (as there may be several different collections in Resources).
ItemCollection.Active = ItemCollection;
}
public void Start()
{
if (ExampleInitialize)
{
TestInitialize();
}
}
/// <summary>
/// Initialize owned items and trader items (just for example).
/// </summary>
public void TestInitialize()
{
var warehouse = new List<Item>();
var inventory = ItemCollection.Active.Items.Select(i => new Item(i.Id, 2)).ToList();
RegisterCallbacks();
WarehouseInventory.Initialize(ref warehouse);
PlayerInventory.Initialize(ref inventory);
if (!WarehouseInventory.SelectAny() && !PlayerInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void Initialize(ref List<Item> playerItems, ref List<Item> storageItems)
{
RegisterCallbacks();
PlayerInventory.Initialize(ref playerItems);
WarehouseInventory.Initialize(ref storageItems);
if (!PlayerInventory.SelectAny() && !WarehouseInventory.SelectAny())
{
ItemInfo.Reset();
}
}
public void RegisterCallbacks()
{
InventoryItem.OnLeftClick = SelectItem;
InventoryItem.OnRightClick = OnDoubleClick;
}
private void OnDoubleClick(Item item)
{
SelectItem(item);
if (PlayerInventory.Items.Contains(item))
{
Take();
}
else if (CanMoveSelectedItem())
{
Put();
}
}
public void SelectItem(Item item)
{
SelectedItem = item;
SetAmount(1);
ItemInfo.Initialize(SelectedItem, SelectedItem.Params.Price * Amount);
Refresh();
}
public void Put()
{
if (!CanMoveSelectedItem()) return;
MoveItem(SelectedItem, PlayerInventory, WarehouseInventory, Amount);
SelectItem(SelectedItem);
AudioSource.PlayOneShot(MoveSound, SfxVolume);
}
public void Take()
{
if (!CanMoveSelectedItem()) return;
MoveItem(SelectedItem, WarehouseInventory, PlayerInventory, Amount);
SelectItem(SelectedItem);
AudioSource.PlayOneShot(MoveSound, SfxVolume);
}
public override void Refresh()
{
if (SelectedItem == null)
{
ItemInfo.Reset();
PutButton.SetActive(false);
TakeButton.SetActive(false);
}
else
{
var stored = WarehouseInventory.Items.Contains(SelectedItem);
PutButton.SetActive(!stored && CanMoveSelectedItem());
TakeButton.SetActive(stored && CanMoveSelectedItem());
}
}
public void SetMinAmount()
{
SetAmount(1);
}
public void IncAmount(int value)
{
SetAmount(Amount + value);
}
public void SetMaxAmount()
{
SetAmount(SelectedItem.Count);
}
public void OnAmountChanged(string value)
{
if (value.IsEmpty()) return;
SetAmount(int.Parse(value));
}
public void OnAmountEndEdit(string value)
{
if (value.IsEmpty())
{
SetAmount(1);
}
}
public void Drop()
{
foreach (var item in PlayerInventory.Items.ToList())
{
if (item.Params.Type != ItemType.Currency && !item.Params.Tags.Contains(ItemTag.Quest))
{
#if TAP_HEROES
if (item.Params.Class == ItemClass.Gunpowder) continue;
#endif
MoveItem(item, PlayerInventory, WarehouseInventory, item.Count);
}
}
AudioSource.PlayOneShot(MoveSound, SfxVolume);
}
private void SetAmount(int amount)
{
Amount = Mathf.Max(1, Mathf.Min(SelectedItem.Count, amount));
AmountInput?.SetTextWithoutNotify(Amount.ToString());
ItemInfo.UpdatePrice(SelectedItem, SelectedItem.Params.Price * Amount, false);
}
protected virtual bool CanMoveSelectedItem()
{
return true;
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: ea396594f36cd004483d10a13d2be0db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: ea396594f36cd004483d10a13d2be0db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: