This commit is contained in:
2026-06-02 08:27:03 +07:00
parent 7889064469
commit a48cd962e1
4232 changed files with 2 additions and 36881 deletions

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 6ed135724a9e5d34698ed0bd33f6e90b
folderAsset: yes
timeCreated: 1468361591
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,93 @@
using Invector.vCharacterController;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
public class vCreateInventoryEditor : EditorWindow
{
GUISkin skin;
GameObject inventoryPrefab;
vItemListData itemListData;
Vector2 rect = new Vector2(500, 240);
Texture2D m_Logo;
[MenuItem("Invector/Inventory/ItemManager (Player Only)", false, 3)]
public static void CreateNewInventory()
{
EditorWindow.GetWindow(typeof(vCreateInventoryEditor), true, "Item Manager Creator", true);
}
void OnGUI()
{
if (!skin) skin = Resources.Load("vSkin") as GUISkin;
GUI.skin = skin;
this.minSize = rect;
m_Logo = Resources.Load("icon_v2") as Texture2D;
GUILayout.BeginVertical("ITEM MANAGER CREATOR", "window", GUILayout.MaxHeight(100), GUILayout.MaxWidth(490));
GUILayout.Label(m_Logo, GUILayout.MaxHeight(25));
GUILayout.BeginVertical("box");
EditorGUILayout.HelpBox("Go to the folder Invector/ItemManager/Prefabs to select a Inventory prefab", MessageType.Info);
inventoryPrefab = EditorGUILayout.ObjectField("Inventory Prefab: ", inventoryPrefab, typeof(GameObject), false) as GameObject;
EditorGUILayout.HelpBox("Go to the folder Invector/ItemManager/ItemListData to select a ItemListData or create a new one in the Inventory menu", MessageType.Info);
itemListData = EditorGUILayout.ObjectField("Item List Data: ", itemListData, typeof(vItemListData), false) as vItemListData;
if (inventoryPrefab != null)
{
EditorGUILayout.HelpBox("Please select a Inventory Prefab, you can find one at the Inventory/Prefabs Folder", MessageType.Warning);
}
GUILayout.EndVertical();
GUILayout.BeginHorizontal("box");
EditorGUILayout.LabelField("Need to know how it works?");
if (GUILayout.Button("Video Tutorial"))
{
Application.OpenURL("https://www.youtube.com/watch?v=1aA_PU9-G-0&index=3&list=PLvgXGzhT_qehtuCYl2oyL-LrWoT7fhg9d");
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (inventoryPrefab != null && itemListData != null)
{
if (Selection.activeGameObject != null && Selection.activeGameObject.GetComponent<vThirdPersonController>() != null)
{
if (GUILayout.Button("Create"))
Create();
}
else
EditorGUILayout.HelpBox("Please select the Player to add this component", MessageType.Warning);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
/// <summary>
/// Created the ItemManager
/// </summary>
void Create()
{
if (Selection.activeGameObject != null)
{
var itemManager = Selection.activeGameObject.AddComponent<vItemManager>();
if (inventoryPrefab != null)
{
var _inventory = PrefabUtility.InstantiatePrefab(inventoryPrefab.gameObject) as GameObject;
_inventory.transform.SetParent(Selection.activeTransform);
}
itemManager.itemListData = itemListData;
vItemManagerUtilities.CreateDefaultEquipPoints(itemManager);
}
else
Debug.Log("Please select the Player to add this component.");
this.Close();
}
}
}

View File

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

View File

@@ -0,0 +1,67 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Linq.Expressions;
using System;
namespace Invector
{
[CustomPropertyDrawer(typeof(vHandler))]
public class vHandlerDrawer : PropertyDrawer
{
vHandler handler = new vHandler();
public int _mHeght;
public GUISkin skin;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (skin == null)
{
skin = Resources.Load("vSkin") as GUISkin;
if (skin == null)
skin = GUI.skin;
}
GUI.skin = skin;
GUI.Box(position, "");
var rect = position;
rect.y += 2f;
rect.x += 2.5f;
rect.width -= 5;
rect.height = 15;
property.isExpanded = GUI.Toggle(rect, property.isExpanded, label, EditorStyles.miniButton);
if (property.isExpanded)
{
rect.y += GetBaseHeight();
rect.width -= 5;
rect.height = 16;
handler.customHandlers = null;
EditorGUI.PropertyField(rect, property.FindPropertyRelative(vEditorHelper.GetPropertyName(() => handler.defaultHandler)));
var customHandlers = property.FindPropertyRelative(vEditorHelper.GetPropertyName(() => handler.customHandlers));
rect.y += GetBaseHeight();
EditorGUI.PropertyField(rect, customHandlers, true);
}
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
var height = 20f;
if (property.isExpanded)
{
height += 40f;
var customHanglersName = vEditorHelper.GetPropertyName(() => handler.customHandlers);
if (property.FindPropertyRelative(customHanglersName).isExpanded)
{
height += 20f + (GetBaseHeight() * property.FindPropertyRelative(customHanglersName).arraySize);
}
}
return height + _mHeght;
}
float GetBaseHeight()
{
return 18f;
}
}
}

View File

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

View File

@@ -0,0 +1,269 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
[CanEditMultipleObjects]
[CustomEditor(typeof(vItemCollection))]
public class vItemCollectionEditor : vEditorBase
{
vItemCollection manager;
SerializedProperty itemReferenceList;
bool inAddItem;
int selectedItem;
List<vItem> filteredItems;
Vector2 scroll;
Rect buttonRect;
List<vItemType> filter = new List<vItemType>();
protected override void OnEnable()
{
base.OnEnable();
manager = (vItemCollection)target;
skin = Resources.Load("vSkin") as GUISkin;
itemReferenceList = serializedObject.FindProperty("items");
}
public override void OnInspectorGUI()
{
var oldSkin = GUI.skin;
serializedObject.Update();
if (skin)
{
GUI.skin = skin;
}
GUILayout.Space(10);
GUI.skin = oldSkin;
base.OnInspectorGUI();
if (skin)
{
GUI.skin = skin;
}
bool usingToolbar = toolbars.Count > 1;
string selectedToolbarName = toolbars[selectedToolBar].title;
if (manager.itemListData && ((usingToolbar && selectedToolbarName.Equals("Item Collection")) || !usingToolbar))
{
GUILayout.BeginVertical("box");
//if (itemReferenceList.arraySize > manager.itemListData.items.Count)
//{
// manager.items.Resize(manager.itemListData.items.Count);
//}
GUILayout.Box("Item Collection " + manager.items.Count);
if (GUILayout.Button("Add Item", EditorStyles.miniButton))
{
PopupWindow.Show(buttonRect, new vItemSelector
(manager.itemListData.items, ref filter, (vItem item) =>//OnSelectItem
{
itemReferenceList.arraySize++;
itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("id").intValue = item.id;
itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("amount").intValue = 1;
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
}
));
}
if (Event.current.type == EventType.Repaint)
{
buttonRect = GUILayoutUtility.GetLastRect();
}
GUIStyle boxStyle = new GUIStyle(GUI.skin.box);
scroll = GUILayout.BeginScrollView(scroll, GUILayout.MinHeight(200), GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
try
{
for (int i = 0; i < manager.items.Count; i++)
{
var item = manager.itemListData.items.Find(t => t.id.Equals(manager.items[i].id));
if (item)
{
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
GUILayout.BeginHorizontal();
var rect = GUILayoutUtility.GetRect(50, 50);
if (item.icon != null)
{
DrawTextureGUI(rect, item.icon, new Vector2(50, 50));
}
var name = " ID " + item.id.ToString("00") + "\n - " + item.name + "\n - " + item.type.ToString();
var content = new GUIContent(name, null, "Click to Open");
GUILayout.Label(content, EditorStyles.miniLabel);
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
GUILayout.Label("Add to EquipArea", EditorStyles.miniLabel);
manager.items[i].addToEquipArea = EditorGUILayout.Toggle("", manager.items[i].addToEquipArea, GUILayout.Width(30));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (manager.items[i].addToEquipArea)
{
GUILayout.Label("EquipArea", EditorStyles.miniLabel);
manager.items[i].indexArea = EditorGUILayout.IntField("", manager.items[i].indexArea, GUILayout.Width(30));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (manager.items[i].addToEquipArea)
{
GUILayout.Label("AutoEquip", EditorStyles.miniLabel);
manager.items[i].autoEquip = EditorGUILayout.Toggle("", manager.items[i].autoEquip, GUILayout.Width(30));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Amount", EditorStyles.miniLabel);
manager.items[i].amount = EditorGUILayout.IntField(manager.items[i].amount, GUILayout.Width(30));
if (manager.items[i].amount < 1)
{
manager.items[i].amount = 1;
}
GUILayout.EndHorizontal();
if (item.attributes.Count > 0)
{
manager.items[i].changeAttributes = GUILayout.Toggle(manager.items[i].changeAttributes, new GUIContent("Change Attributes", "This is a override of the original item attributes"), EditorStyles.miniButton, GUILayout.ExpandWidth(true));
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
if (GUILayout.Button("x", GUILayout.Width(25), GUILayout.Height(25)))
{
itemReferenceList.DeleteArrayElementAtIndex(i);
EditorUtility.SetDirty(target);
serializedObject.ApplyModifiedProperties();
break;
}
GUILayout.EndHorizontal();
Color backgroundColor = GUI.backgroundColor;
GUI.backgroundColor = Color.clear;
var _rec = GUILayoutUtility.GetLastRect();
_rec.width -= 100;
EditorGUIUtility.AddCursorRect(_rec, MouseCursor.Link);
if (GUI.Button(_rec, ""))
{
if (manager.itemListData.inEdition)
{
if (vItemListWindow.Instance != null)
{
vItemListWindow.SetCurrentSelectedItem(manager.itemListData.items.IndexOf(item));
}
else
{
vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item));
}
}
else
{
vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item));
}
}
GUILayout.Space(7);
GUI.backgroundColor = backgroundColor;
if (item.attributes != null && item.attributes.Count > 0)
{
if (manager.items[i].changeAttributes)
{
if (GUILayout.Button("Reset", EditorStyles.miniButton))
{
manager.items[i].attributes = null;
}
if (manager.items[i].attributes == null)
{
manager.items[i].attributes = item.attributes.CopyAsNew();
}
else if (manager.items[i].attributes.Count != item.attributes.Count)
{
manager.items[i].attributes = item.attributes.CopyAsNew();
}
else
{
for (int a = 0; a < manager.items[i].attributes.Count; a++)
{
GUILayout.BeginHorizontal();
GUILayout.Label(manager.items[i].attributes[a].name.ToString());
manager.items[i].attributes[a].value = EditorGUILayout.IntField(manager.items[i].attributes[a].value, GUILayout.MaxWidth(60));
GUILayout.EndHorizontal();
}
}
}
}
GUILayout.EndVertical();
}
else
{
itemReferenceList.DeleteArrayElementAtIndex(i);
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
break;
}
}
}
catch
{
}
GUILayout.EndScrollView();
GUI.skin.box = boxStyle;
GUILayout.EndVertical();
if (GUI.changed)
{
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
}
}
if (GUI.changed)
{
EditorUtility.SetDirty(target);
}
serializedObject.ApplyModifiedProperties();
GUI.skin = oldSkin;
}
GUIContent[] GetItemContents(List<vItem> items)
{
GUIContent[] names = new GUIContent[items.Count];
for (int i = 0; i < items.Count; i++)
{
var texture = items[i].icon != null ? items[i].icon.texture : null;
names[i] = new GUIContent(items[i].name, texture, items[i].description);
}
return names;
}
List<vItem> GetItemByFilter(List<vItem> items, List<vItemType> filter)
{
return items.FindAll(i => filter.Contains(i.type));
}
void DrawTextureGUI(Rect position, Sprite sprite, Vector2 size)
{
Rect spriteRect = new Rect(sprite.rect.x / sprite.texture.width, sprite.rect.y / sprite.texture.height,
sprite.rect.width / sprite.texture.width, sprite.rect.height / sprite.texture.height);
Vector2 actualSize = size;
actualSize.y *= (sprite.rect.height / sprite.rect.width);
GUI.DrawTextureWithTexCoords(new Rect(position.x, position.y + (size.y - actualSize.y) / 2, actualSize.x, actualSize.y), sprite.texture, spriteRect);
}
}
}

View File

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

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Invector.vItemManager
{
/// <summary>
/// This attribute is used to draw aditional custom editor like a ToolBar for <see cref="vItem"/> in partial classes of the <see cref="vItemDrawer"/> using <see cref="vItemDrawer.OnDrawItem"/>
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class vItemDrawerToolBarAttribute : Attribute
{
public string title;
public vItemDrawerToolBarAttribute(string title)
{
this.title = title;
}
}
}

View File

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

View File

@@ -0,0 +1,322 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
[CustomEditor(typeof(vItem), true)]
public class vItemEditor : UnityEditor.Editor
{
protected virtual string[] excludedProperties => new string[] { "m_Script" };
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawPropertiesExcluding(serializedObject, excludedProperties);
serializedObject.ApplyModifiedProperties();
}
}
[Serializable]
public partial class vItemDrawer
{
public vItem item;
protected bool inAddAttribute;
protected vItemAttributes attribute;
protected int attributeValue;
protected int indexToolbar;
protected bool inEditName;
protected string currentName;
protected vItemEditor defaultEditor;
public List<ToolBars> itemToolBars;
public delegate void OnDrawItem(ref List<vItem> items, bool showObject = true, bool editName = false);
[Serializable]
public class ToolBars
{
public string title;
public OnDrawItem onDraw;
public ToolBars(string title, OnDrawItem onDraw)
{
this.title = title;
this.onDraw = onDraw;
}
}
public vItemDrawer(vItem item)
{
this.item = item;
defaultEditor = (vItemEditor)UnityEditor.Editor.CreateEditor(this.item, typeof(vItemEditor));
FindDrawers();
}
void FindDrawers()
{
var methods = this.GetType().GetMethods().Where(m => m.GetCustomAttributes(typeof(vItemDrawerToolBarAttribute), true).Length > 0).ToArray();
itemToolBars = new List<ToolBars>();
itemToolBars.Add(new ToolBars("Properties", new OnDrawItem(DrawAllProperties)));
for (int i = 0; i < methods.Length; i++)
{
string title = (methods[i].GetCustomAttributes(typeof(vItemDrawerToolBarAttribute), true)[0] as vItemDrawerToolBarAttribute).title;
OnDrawItem onDraw = (OnDrawItem)Delegate.CreateDelegate(typeof(OnDrawItem), this, methods[i]);
itemToolBars.Add(new ToolBars(title, onDraw));
}
}
private string[] titles = new string[] { "Properties" };
public string[] ToolBarTitles()
{
if (titles == null || titles.Length != itemToolBars.Count)
{
titles = new string[itemToolBars.Count];
for (int i = 0; i < itemToolBars.Count; i++)
{
titles[i] = itemToolBars[i].title;
}
}
return titles;
}
public virtual void DrawItem(ref List<vItem> items, bool showObject = true, bool editName = false)
{
if (!item) return;
SerializedObject _item = new SerializedObject(item);
_item.Update();
try
{
if (itemToolBars.Count > 1) indexToolbar = GUILayout.Toolbar(indexToolbar, ToolBarTitles());
itemToolBars[indexToolbar].onDraw(ref items, showObject, editName);
}
catch
{
FindDrawers();
}
if (GUI.changed || _item.ApplyModifiedProperties())
{
EditorUtility.SetDirty(item);
}
}
public virtual void DrawAllProperties(ref List<vItem> items, bool showObject, bool editName)
{
DrawItemHeader(ref items, showObject, editName);
DrawItemProperties();
DrawDefaultProperties();
}
public virtual void DrawItemHeader(ref List<vItem> items, bool showObject, bool editName)
{
if (showObject)
EditorGUILayout.ObjectField(item, typeof(vItem), false);
if (editName)
item.name = EditorGUILayout.TextField("Item name", item.name);
else
{
GUILayout.BeginHorizontal("box");
GUILayout.Label(item.name, GUILayout.ExpandWidth(true));
if (!inEditName && GUILayout.Button("EditName", EditorStyles.miniButton))
{
currentName = item.name;
inEditName = true;
}
GUILayout.EndHorizontal();
}
if (inEditName)
{
var sameItemName = items.Find(i => i.name == currentName && i != item);
currentName = EditorGUILayout.TextField("New Name", currentName);
GUILayout.BeginHorizontal("box");
if (sameItemName == null && !string.IsNullOrEmpty(currentName) && GUILayout.Button("OK", EditorStyles.miniButton, GUILayout.MinWidth(60)))
{
item.name = currentName;
inEditName = false;
}
if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
{
inEditName = false;
}
GUILayout.EndHorizontal();
if (sameItemName != null)
EditorGUILayout.HelpBox("This name already exist", MessageType.Error);
if (string.IsNullOrEmpty(currentName))
EditorGUILayout.HelpBox("This name can not be empty", MessageType.Error);
}
}
public virtual void DrawItemProperties()
{
GUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Description");
item.description = EditorGUILayout.TextArea(item.description);
item.type = (vItemType)EditorGUILayout.EnumPopup("Item Type", item.type);
item.stackable = EditorGUILayout.Toggle("Stackable", item.stackable);
if (item.stackable)
{
if (item.maxStack <= 0) item.maxStack = 1;
item.createNewItem = true;
item.maxStack = EditorGUILayout.IntField("Max Stack", item.maxStack);
}
else
{
EditorGUILayout.HelpBox("True: Add a new item creating multiple items of the same id \nFalse: Do not create a new item but call the OnCollectItemRef if you already have one.", MessageType.Info);
item.createNewItem = EditorGUILayout.Toggle(new GUIContent("Create new Item"), item.createNewItem);
item.maxStack = 1;
}
GUILayout.EndVertical();
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
GUILayout.Label("Icon");
item.icon = (Sprite)EditorGUILayout.ObjectField(item.icon, typeof(Sprite), false);
var rect = GUILayoutUtility.GetRect(40, 40);
if (item.icon != null)
{
DrawTextureGUI(rect, item.icon, new Vector2(40, 40));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.BeginVertical("box");
GUILayout.Label("Spawn Object");
item.originalObject = (GameObject)EditorGUILayout.ObjectField(item.originalObject, typeof(GameObject), false);
GUILayout.EndVertical();
GUILayout.BeginVertical("box");
GUILayout.Label("Drop Object");
item.dropObject = (GameObject)EditorGUILayout.ObjectField(item.dropObject, typeof(GameObject), false);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
DrawAttributes();
}
public virtual void DrawDefaultProperties()
{
GUILayout.BeginVertical("box");
GUILayout.Box(new GUIContent("Custom Settings", "This area is used for additional properties\n in vItem Properties in defaultInspector region"));
defaultEditor.OnInspectorGUI();
GUILayout.EndVertical();
}
public virtual void DrawAttributes()
{
try
{
GUILayout.BeginVertical("box");
GUILayout.Box("Attributes", GUILayout.ExpandWidth(true));
EditorGUILayout.Space();
if (!inAddAttribute && GUILayout.Button("Add Attribute", EditorStyles.miniButton))
inAddAttribute = true;
if (inAddAttribute)
{
GUILayout.BeginHorizontal("box");
attribute = (vItemAttributes)EditorGUILayout.EnumPopup(attribute);
EditorGUILayout.LabelField("Value", GUILayout.MinWidth(60));
attributeValue = EditorGUILayout.IntField(attributeValue);
GUILayout.EndHorizontal();
if (item.attributes != null && item.attributes.Contains(attribute))
{
EditorGUILayout.HelpBox("This attribute already exist ", MessageType.Error);
if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
{
inAddAttribute = false;
}
}
else
{
GUILayout.BeginHorizontal("box");
if (GUILayout.Button("Add", EditorStyles.miniButton, GUILayout.MinWidth(60)))
{
item.attributes.Add(new vItemAttribute(attribute, attributeValue));
attributeValue = 0;
inAddAttribute = false;
}
if (GUILayout.Button("Cancel", EditorStyles.miniButton, GUILayout.MinWidth(60)))
{
attributeValue = 0;
inAddAttribute = false;
}
GUILayout.EndHorizontal();
}
}
EditorGUILayout.Space();
for (int i = 0; i < item.attributes.Count; i++)
{
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
item.attributes[i].isOpen = EditorGUILayout.Foldout(item.attributes[i].isOpen, item.attributes[i].name.ToString());
item.attributes[i].value = EditorGUILayout.IntField(item.attributes[i].value);
EditorGUILayout.Space();
if (GUILayout.Button("x", GUILayout.MaxWidth(30)))
{
item.attributes.RemoveAt(i);
GUILayout.EndHorizontal();
break;
}
GUILayout.EndHorizontal();
if (item.attributes[i].isOpen)
{
EditorGUILayout.HelpBox("Open the ItemEnumsEditor to edit this format", MessageType.Info);
string format = item.attributes[i].displayFormat;
GUILayout.BeginHorizontal();
GUILayout.Label("Display format");
GUILayout.Label(format, EditorStyles.whiteBoldLabel);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
}
GUILayout.EndVertical();
}
catch
{
Debug.Log("ERROR");
}
}
public virtual void DrawTextureGUI(Rect position, Sprite sprite, Vector2 size)
{
Rect spriteRect = new Rect(sprite.rect.x / sprite.texture.width, sprite.rect.y / sprite.texture.height,
sprite.rect.width / sprite.texture.width, sprite.rect.height / sprite.texture.height);
Vector2 actualSize = size;
actualSize.y *= (sprite.rect.height / sprite.rect.width);
GUI.DrawTextureWithTexCoords(new Rect(position.x, position.y + (size.y - actualSize.y) / 2, actualSize.x, actualSize.y), sprite.texture, spriteRect);
}
public static List<T> FindAssetsByType<T>() where T : UnityEngine.Object
{
List<T> assets = new List<T>();
string[] guids = AssetDatabase.FindAssets(string.Format("t:{0}", typeof(T)));
for (int i = 0; i < guids.Length; i++)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
T asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
if (asset != null)
{
assets.Add(asset);
}
}
return assets;
}
}
}

View File

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

View File

@@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
//public static class vItemEnumHelper
//{
// public static string GetEnumDescription(this Enum value)
// {
// FieldInfo fi = value.GetType().GetField(value.ToString());
// DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
// if (attributes != null && attributes.Any())
// {
// return attributes.First().Description;
// }
// return value.ToString();
// }
//}
public class vItemEnumsWindow : EditorWindow
{
public vItemEnumsList[] datas;
public List<string> _itemTypeNames = new List<string>();
public List<string> _itemAttributeNames = new List<string>();
public List<string> _itemTypeEnumFormats = new List<string>();
public List<string> _itemAttributesEnumFormats = new List<string>();
public List<DynamicEnum.vItemEnumsListEditor> itemEnumEditorList = new List<DynamicEnum.vItemEnumsListEditor>();
public GUISkin skin;
public Vector2 scrollTypes,scrollAttributes;
public Vector2 scrollList;
public static vItemEnumsWindow instance;
[MenuItem("Invector/Inventory/ItemEnums/Open ItemEnums Editor")]
public static void CreateWindow()
{
if (instance == null)
{
var window = vItemEnumsWindow.GetWindow<vItemEnumsWindow>("Item Enums", true);
instance = window;
window.skin = Resources.Load("vSkin") as GUISkin;
#region Get all vItemType values of current Enum
try
{
window._itemTypeNames = Enum.GetNames(typeof(vItemType)).vToList();
for (int i = 0; i < window._itemTypeNames.Count; i++)
{
vItemType att = (vItemType)Enum.Parse(typeof(vItemType), (window._itemTypeNames[i]));
window._itemTypeEnumFormats.Add(att.DisplayFormat());
}
}
catch
{
}
#endregion
#region Get all vItemAttributes values of current Enum
try
{
window._itemAttributeNames = Enum.GetNames(typeof(vItemAttributes)).vToList();
for(int i = 0;i<window._itemAttributeNames.Count;i++)
{
vItemAttributes att = (vItemAttributes)Enum.Parse(typeof(vItemAttributes),(window._itemAttributeNames[i]));
window._itemAttributesEnumFormats.Add(att.DisplayFormat());
}
}
catch
{
}
#endregion
window.datas = Resources.LoadAll<vItemEnumsList>("");
for(int i=0;i<window.datas.Length;i++)
{
window.itemEnumEditorList.Add(DynamicEnum.vItemEnumsListEditor.CreateEditor(window.datas[i]) as DynamicEnum.vItemEnumsListEditor);
}
window.minSize = new Vector2(460, 600);
}
}
void OnGUI()
{
if (skin) GUI.skin = skin;
this.minSize = new Vector2(460, 600);
GUILayout.BeginVertical("box");
DrawEnums();
GUILayout.EndVertical();
GUILayout.BeginVertical("box");
GUILayout.Box("Edit Enums");
scrollList = GUILayout.BeginScrollView(scrollList, GUILayout.ExpandWidth(true), GUILayout.MinHeight(100), GUILayout.MaxHeight(600));
EditorGUILayout.HelpBox("**Format : Rich Text Format usage to create custom text format to display the Item Enums in the inventory like a\n" +
" Special Tags : (NAME) : dipllay name of the Enum\n" +
" (VALUE): display value of the Attribute (only for Item Attribute Enum)\n" +
"Keep Format empty to use Default display", MessageType.Info);
for (int i = 0; i < itemEnumEditorList.Count; i++)
{
GUILayout.BeginVertical("box");
EditorGUILayout.ObjectField(itemEnumEditorList[i].serializedObject.targetObject, typeof(vItemEnumsList), false);
itemEnumEditorList[i].serializedObject.Update();
itemEnumEditorList[i].DrawEnumList();
if (GUI.changed)
{
itemEnumEditorList[i].serializedObject.ApplyModifiedProperties();
}
GUILayout.EndVertical();
GUILayout.Space(10);
GUILayout.Box("", GUILayout.Height(5));
GUILayout.Space(10);
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
if (GUILayout.Button(new GUIContent("Refresh ItemEnums", "Save and refesh changes to vItemEnums")))
{
vItemEnumsBuilder.RefreshItemEnums();
}
}
private void DrawEnums()
{
GUILayout.Box("vItemEnums");
int size = _itemTypeNames.Count > _itemAttributeNames.Count ? _itemTypeNames.Count : _itemAttributeNames.Count;
GUILayout.BeginHorizontal();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal(GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));
#region Item Type current
GUILayout.BeginVertical("box",GUILayout.ExpandWidth(true));
GUILayout.Box("Item Types (" + (_itemTypeNames.Count) + ")", GUILayout.ExpandWidth(true));
scrollTypes = GUILayout.BeginScrollView(scrollTypes, GUILayout.MinHeight(Mathf.Clamp(size * EditorGUIUtility.singleLineHeight, 10, 500)));
for (int i = 0; i < _itemTypeNames.Count; i++)
{
GUILayout.Label(_itemTypeNames[i], EditorStyles.miniBoldLabel, GUILayout.ExpandWidth(true));
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
#endregion
#region Item Attribute current
GUILayout.BeginVertical("box", GUILayout.ExpandWidth(true));
GUILayout.Box("Item Attributes ("+(_itemAttributeNames.Count)+")", GUILayout.ExpandWidth(true));
scrollAttributes = GUILayout.BeginScrollView(scrollAttributes, GUILayout.MinHeight(Mathf.Clamp(size * EditorGUIUtility.singleLineHeight, 10, 500)));
for (int i = 0; i < _itemAttributeNames.Count; i++)
{
GUILayout.Label(_itemAttributeNames[i], EditorStyles.miniBoldLabel,GUILayout.ExpandWidth(true));
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
#endregion
GUILayout.EndHorizontal();
}
void DrawItemEnumListData(vItemEnumsList data)
{
SerializedObject _data = new SerializedObject(data);
_data.Update();
GUILayout.BeginVertical("box");
GUILayout.Box(data.name, GUILayout.ExpandWidth(true));
EditorGUILayout.ObjectField(data, typeof(vItemEnumsList), false);
GUILayout.BeginHorizontal();
#region Item Types
var itemTypeEnumValueList = _data.FindProperty("itemTypeEnumValues");
GUILayout.BeginVertical("box", GUILayout.Width(200));
GUILayout.BeginHorizontal("box", GUILayout.ExpandWidth(true));
GUILayout.Label("Item Types", EditorStyles.miniBoldLabel);
EditorGUILayout.PropertyField(itemTypeEnumValueList.FindPropertyRelative("Array.size"), GUIContent.none);
GUILayout.EndHorizontal();
var labelWidht = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 30f;
var color = GUI.color;
for (int i = 0; i < itemTypeEnumValueList.arraySize; i++)
{
if (_itemTypeNames.Contains(itemTypeEnumValueList.GetArrayElementAtIndex(i).stringValue))
GUI.color = Color.gray;
else GUI.color = color;
EditorGUILayout.PropertyField(itemTypeEnumValueList.GetArrayElementAtIndex(i), new GUIContent(i.ToString()));
}
GUILayout.EndVertical();
#endregion
#region Item Attributes
GUI.color = color;
var itemAttributesEnumValuesList = _data.FindProperty("itemAttributesEnumValues");
GUILayout.BeginVertical("box", GUILayout.Width(200));
GUILayout.BeginHorizontal("box", GUILayout.ExpandWidth(true));
GUILayout.Label("Item Attributes", EditorStyles.miniBoldLabel);
EditorGUILayout.PropertyField(itemAttributesEnumValuesList.FindPropertyRelative("Array.size"), GUIContent.none);
GUILayout.EndHorizontal();
for (int i = 0; i < itemAttributesEnumValuesList.arraySize; i++)
{
if (_itemAttributeNames.Contains(itemAttributesEnumValuesList.GetArrayElementAtIndex(i).stringValue))
GUI.color = Color.gray;
else GUI.color = color;
EditorGUILayout.PropertyField(itemAttributesEnumValuesList.GetArrayElementAtIndex(i), new GUIContent(i.ToString()));
}
GUILayout.EndVertical();
#endregion
GUILayout.EndHorizontal();
GUILayout.EndVertical();
_data.ApplyModifiedProperties();
if (_data.ApplyModifiedProperties())
EditorUtility.SetDirty(data);
EditorGUIUtility.labelWidth = labelWidht;
GUI.color = color;
}
}
}

View File

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

View File

@@ -0,0 +1,109 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
[CustomEditor(typeof(vItemListData))]
public class vItemListEditor : UnityEditor.Editor
{
[SerializeField]
protected GUISkin skin;
[SerializeField]
protected vItemListData itemList;
protected Texture2D m_Logo = null;
void OnEnable()
{
itemList = (vItemListData)target;
skin = Resources.Load("vSkin") as GUISkin;
m_Logo = (Texture2D)Resources.Load("icon_v2", typeof(Texture2D));
}
[MenuItem("Invector/Inventory/Create New ItemListData")]
static void CreateNewListData()
{
vItemListData listData = ScriptableObject.CreateInstance<vItemListData>();
AssetDatabase.CreateAsset(listData, "Assets/ItemListData.asset");
}
public override void OnInspectorGUI()
{
if (skin) GUI.skin = skin;
serializedObject.Update();
GUI.enabled = !Application.isPlaying;
GUILayout.BeginVertical("Item List", "window");
GUILayout.Label(m_Logo, GUILayout.MaxHeight(25));
OpenCloseItemWindow();
GUILayout.Space(20);
if (GUILayout.Button(itemList.itemsHidden ? "Show items in Hierarchy" : "Hide items in Hierarchy"))
{
ShowAllItems();
}
GUILayout.EndVertical();
if (GUI.changed || serializedObject.ApplyModifiedProperties())
{
EditorUtility.SetDirty(target);
}
}
protected virtual void OpenCloseItemWindow()
{
if (itemList.itemsHidden && !itemList.inEdition && GUILayout.Button("Edit Items in List"))
{
vItemListWindow.CreateWindow(itemList);
}
else if (itemList.inEdition)
{
if (vItemListWindow.Instance != null)
{
if (vItemListWindow.Instance.itemList == null)
{
vItemListWindow.Instance.Close();
}
else
EditorGUILayout.HelpBox("The Item List Window is open", MessageType.Info);
}
else
{
itemList.inEdition = false;
}
}
}
public virtual void ShowAllItems()
{
if (itemList.itemsHidden)
{
foreach (vItem item in itemList.items)
{
item.hideFlags = HideFlags.None;
EditorUtility.SetDirty(item);
}
itemList.itemsHidden = false;
}
else
{
foreach (vItem item in itemList.items)
{
item.hideFlags = HideFlags.HideInHierarchy;
EditorUtility.SetDirty(item);
}
itemList.itemsHidden = true;
}
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
AssetDatabase.SaveAssets();
}
}
}

View File

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

View File

@@ -0,0 +1,570 @@
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
public class vItemListWindow : EditorWindow
{
public static vItemListWindow Instance;
public vItemListData itemList;
[SerializeField]
public GUISkin skin;
public SerializedObject serializedObject;
public vItem addItem;
public vItemDrawer addItemDrawer;
public vItemDrawer currentItemDrawer;
public bool inAddItem;
public bool inDragItens;
public bool openAttributeList;
public bool inCreateAttribute;
public string attributeName;
public int indexSelected;
public Vector2 scroolView;
public Vector2 attributesScroll;
public Texture2D m_Logo = null;
public System.Action<int> OnSelectItem;
public Vector2 addItemScroolView;
public List<vItemType> filter = new List<vItemType>();
public string search = "";
bool isOpenFilter;
public List<vItem> newItems = new List<vItem>();
public Vector2 newItemsScrool;
protected virtual void OnEnable()
{
m_Logo = (Texture2D)Resources.Load("icon_v2", typeof(Texture2D));
}
public static void CreateWindow(vItemListData itemList)
{
vItemListWindow window = (vItemListWindow)EditorWindow.GetWindow(typeof(vItemListWindow), false, "ItemList Editor");
Instance = window;
window.itemList = itemList;
LoadSkin(window);
Instance.Init();
}
protected static void LoadSkin(vItemListWindow window)
{
window.skin = Resources.Load("vSkin") as GUISkin;
}
public static void CreateWindow(vItemListData itemList, int firtItemSelected)
{
vItemListWindow window = (vItemListWindow)EditorWindow.GetWindow(typeof(vItemListWindow), false, "ItemList Editor");
Instance = window;
window.itemList = itemList;
LoadSkin(window);
Instance.Init(firtItemSelected);
}
public static void CreateWindow(vItemListData itemList, System.Action<int> OnSelectItem)
{
vItemListWindow window = (vItemListWindow)EditorWindow.CreateInstance<vItemListWindow>();
// Instance = window;
window.itemList = itemList;
LoadSkin(window);
window.OnSelectItem = OnSelectItem;
window.titleContent = new GUIContent("ItemList Selector");
window.Show();
window.Init();
}
public virtual void Init()
{
serializedObject = new SerializedObject(itemList);
var subAssets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(itemList));
skin = Resources.Load("vSkin") as GUISkin;
if (subAssets.Length > 1)
{
for (int i = subAssets.Length - 1; i >= 0; i--)
{
var item = subAssets[i] as vItem;
if (item && !itemList.items.Contains(item))
{
item.id = GetUniqueID();
itemList.items.Add(item);
}
}
EditorUtility.SetDirty(itemList);
OrderByID(ref itemList.items);
}
itemList.inEdition = true;
this.Show();
}
public virtual void Init(int firtItemSelected)
{
Init();
SetCurrentSelectedItem(firtItemSelected);
}
public virtual void OnGUI()
{
if (skin) GUI.skin = skin;
var _color = GUI.color;
if (OnSelectItem != null)
GUI.color = Color.red;
GUILayout.BeginVertical("Item List", "window");
GUI.color = _color;
GUILayout.Label(m_Logo, GUILayout.MaxHeight(25));
GUILayout.BeginVertical("box");
GUI.enabled = !Application.isPlaying;
itemList = EditorGUILayout.ObjectField("ItemListData", itemList, typeof(vItemListData), false) as vItemListData;
this.minSize = new Vector2(250, minSize.y);
if (serializedObject == null && itemList != null)
{
serializedObject = new SerializedObject(itemList);
}
else if (itemList == null)
{
GUILayout.EndVertical();
return;
}
serializedObject.Update();
if (OnSelectItem == null)
{
if (!inDragItens && GUILayout.Button("Add Items"))
{
inDragItens = true;
}
if (!inAddItem && GUILayout.Button("Create New Item"))
{
addItem = ScriptableObject.CreateInstance<vItem>();
addItem.name = "New Item";
currentItemDrawer = null;
inAddItem = true;
}
if (inDragItens)
{
GUILayout.BeginVertical("window");
EditorGUILayout.HelpBox("You can add items from other lists by selecting other lists in the ProjectWindow, click on 'Show items in Hierarchy' and drag & drop the item to the field bellow", MessageType.Info);
EditorGUILayout.HelpBox("New items will have their IDs modified if Same ID exits in Items List", MessageType.Warning);
DrawDragBox(ref newItems);
GUILayout.BeginVertical();
newItemsScrool = GUILayout.BeginScrollView(newItemsScrool, false, false, GUILayout.MaxHeight(Mathf.Clamp(newItems.Count * 25, 0, 500)));
OrderByID(ref newItems);
for (int i = 0; i < newItems.Count; i++)
{
GUILayout.BeginHorizontal();
if (itemList.items.Find(it => it.name.ToClearUpper().Equals(newItems[i].name.ToClearUpper())))
{
GUI.color = Color.red;
GUILayout.Label("EXIST"); EditorGUILayout.ObjectField(newItems[i], typeof(vItem), false);
}
else
{
GUI.color = Color.white;
EditorGUILayout.ObjectField(newItems[i], typeof(vItem), false);
}
GUI.color = Color.white;
if (GUILayout.Button("x", EditorStyles.miniButton, GUILayout.Width(20)))
{
newItems.RemoveAt(i);
i--;
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
GUILayout.BeginHorizontal();
GUI.enabled = newItems.Count > 0;
if (GUILayout.Button("ADD", GUILayout.MinWidth(50), GUILayout.MaxWidth(100)))
{
AddItem(newItems);
newItems.Clear();
inDragItens = false;
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
if (GUILayout.Button("CLEAR", GUILayout.MinWidth(50), GUILayout.MaxWidth(100)))
{
newItems.Clear();
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("CANCEL", GUILayout.MinWidth(50), GUILayout.MaxWidth(100)))
{
inDragItens = false;
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
if (inAddItem)
{
DrawAddItem();
}
if (GUILayout.Button("Open ItemEnums Editor"))
{
vItemEnumsWindow.CreateWindow();
}
}
GUILayout.Space(10);
GUILayout.EndVertical();
GUILayout.Box(itemList.items.Count.ToString("00") + " Items");
DrawFilter();
scroolView = GUILayout.BeginScrollView(scroolView, GUILayout.ExpandWidth(true));
int count = 0;
for (int i = 0; i < itemList.items.Count; i++)
{
if (itemList.items[i] != null && FilterItems(itemList.items[i]))
{
Color color = GUI.color;
GUI.color = currentItemDrawer != null && currentItemDrawer.item == itemList.items[i] ? Color.green : color;
GUILayout.BeginVertical("box");
{
GUI.color = color;
GUILayout.BeginHorizontal();
{
var texture = itemList.items[i].iconTexture;
var name = " ID " + itemList.items[i].id.ToString("00") + "\n - " + itemList.items[i].name + "\n - " + itemList.items[i].type.ToString();
var content = new GUIContent(name, texture, currentItemDrawer != null && currentItemDrawer.item == itemList.items[i] ? "Click to Close" : "Click to Open");
GUIStyle boxStyle = new GUIStyle(GUI.skin.box);
GUI.skin.box.alignment = TextAnchor.UpperLeft;
GUI.skin.box.fontStyle = FontStyle.Italic;
GUI.skin.box.fontSize = 11;
if (GUILayout.Button(content, "label", GUILayout.Height(60), GUILayout.MinWidth(60)))
{
if (OnSelectItem != null)
{
OnSelectItem.Invoke(i);
OnSelectItem = null;
this.Close();
}
else
{
GUI.FocusControl("clearFocus");
scroolView.y = 1 + count * 60;
GetItemDrawer(i);
}
}
if (OnSelectItem == null)
{
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
GUI.skin.box = boxStyle;
var duplicateImage = Resources.Load("duplicate") as Texture;
if (GUILayout.Button(new GUIContent("", duplicateImage, "Duplicate Item"), GUILayout.MaxWidth(45), GUILayout.Height(45)))
{
if (EditorUtility.DisplayDialog("Duplicate the " + itemList.items[i].name,
"Are you sure you want to duplicate this item? ", "Duplicate", "Cancel"))
{
DuplicateItem(itemList.items[i]);
GUILayout.EndHorizontal();
Repaint();
break;
}
}
if (GUILayout.Button(new GUIContent("x", "Delete Item"), GUILayout.MaxWidth(20), GUILayout.Height(45)))
{
if (EditorUtility.DisplayDialog("Delete the " + itemList.items[i].name,
"Are you sure you want to delete this item? ", "Delete", "Cancel"))
{
var item = itemList.items[i];
itemList.items.RemoveAt(i);
DestroyImmediate(item, true);
OrderByID(ref itemList.items);
AssetDatabase.SaveAssets();
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(itemList);
GUILayout.EndHorizontal();
Repaint();
break;
}
}
}
}
GUILayout.EndHorizontal();
GUI.color = color;
if (currentItemDrawer != null && currentItemDrawer.item == itemList.items[i] && itemList.items.Contains(currentItemDrawer.item))
{
currentItemDrawer.DrawItem(ref itemList.items, false);
}
}
GUILayout.EndVertical();
count++;
}
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
if (GUI.changed || serializedObject.ApplyModifiedProperties())
{
EditorUtility.SetDirty(itemList);
}
}
void DrawDragBox<T>(ref List<T> list) where T : Object
{
//var dragAreaGroup = GUILayoutUtility.GetRect(0f, 35f, GUILayout.ExpandWidth(true));
GUI.skin.box.alignment = TextAnchor.MiddleCenter;
GUI.skin.box.normal.textColor = Color.white;
//GUILayout.BeginVertical("window");
GUILayout.Box("Drag yours Items here!", "box", GUILayout.MinHeight(50), GUILayout.ExpandWidth(true));
var dragAreaGroup = GUILayoutUtility.GetLastRect();
//GUILayout.EndVertical();
switch (Event.current.type)
{
case EventType.DragUpdated:
case EventType.DragPerform:
if (list == null) list = new List<T>();
if (!dragAreaGroup.Contains(Event.current.mousePosition))
break;
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (Event.current.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
foreach (var dragged in DragAndDrop.objectReferences)
{
try
{
var newObject = (T)dragged;
if (newObject == null || list.Contains(newObject) || list.Exists(l => l.name.ToClearUpper().Equals(newObject.name.ToClearUpper())))
continue;
list.Add(newObject);
}
catch { };
}
}
serializedObject.ApplyModifiedProperties();
Event.current.Use();
break;
}
}
public virtual void DrawFilter()
{
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
isOpenFilter = EditorGUILayout.Foldout(isOpenFilter, "Filters (" + filter.Count + ")");
if (GUILayout.Button("+", GUILayout.Width(20), GUILayout.Height(15)))
{
isOpenFilter = true;
filter.Add((vItemType)0);
}
GUILayout.EndHorizontal();
if (isOpenFilter)
{
for (int i = 0; i < filter.Count; i++)
{
GUILayout.BeginHorizontal();
filter[i] = (vItemType)EditorGUILayout.EnumPopup(filter[i]);
if (GUILayout.Button("-", GUILayout.Width(20), GUILayout.Height(15)))
{
filter.RemoveAt(i);
GUILayout.EndHorizontal();
break;
}
GUILayout.EndHorizontal();
}
}
GUILayout.EndVertical();
GUILayout.BeginHorizontal();
search = GUILayout.TextField(search, GUILayout.Width(this.position.width - 50));
GUILayout.Label(EditorGUIUtility.IconContent("Search Icon"), GUILayout.Height(20));
GUILayout.EndHorizontal();
}
public virtual bool FilterItems(vItem item)
{
return ((filter.Count == 0 || filter.Contains(item.type)) && (string.IsNullOrEmpty(search) || item.name.ToLower().Contains(search.ToLower())));
}
protected virtual void GetItemDrawer(int itemListIndex)
{
currentItemDrawer = currentItemDrawer != null ? currentItemDrawer.item == itemList.items[itemListIndex] ? null : new vItemDrawer(itemList.items[itemListIndex]) : new vItemDrawer(itemList.items[itemListIndex]);
}
public static void SetCurrentSelectedItem(int index)
{
if (Instance != null && Instance.itemList != null && Instance.itemList.items != null && Instance.itemList.items.Count > 0 && index < Instance.itemList.items.Count)
{
Instance.currentItemDrawer = Instance.currentItemDrawer != null ? Instance.currentItemDrawer.item == Instance.itemList.items[index] ? null : new vItemDrawer(Instance.itemList.items[index]) : new vItemDrawer(Instance.itemList.items[index]);
Instance.scroolView.y = 1 + index * 60;
Instance.Repaint();
}
}
protected virtual void OnDestroy()
{
if (itemList)
{
itemList.inEdition = false;
}
}
protected virtual void DrawAddItem()
{
GUILayout.BeginVertical("box");
if (addItem != null)
{
addItemScroolView = EditorGUILayout.BeginScrollView(addItemScroolView, false, false);
if (addItemDrawer == null || addItemDrawer.item == null || addItemDrawer.item != addItem)
addItemDrawer = new vItemDrawer(addItem);
bool isValid = true;
if (addItemDrawer != null)
{
GUILayout.Box("Create Item Window");
addItemDrawer.DrawItem(ref itemList.items, false, true);
}
if (string.IsNullOrEmpty(addItem.name))
{
isValid = false;
EditorGUILayout.HelpBox("This item name cant be null or empty,please type a name", MessageType.Error);
}
if (itemList.items.FindAll(item => item.name.Equals(addItemDrawer.item.name)).Count > 0)
{
isValid = false;
EditorGUILayout.HelpBox("This item name already exists", MessageType.Error);
}
EditorGUILayout.EndScrollView();
GUILayout.BeginHorizontal("box", GUILayout.ExpandWidth(false));
if (isValid && GUILayout.Button("Create"))
{
AddItemCreated();
}
if (GUILayout.Button("Cancel"))
{
addItem = null;
inAddItem = false;
addItemDrawer = null;
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(itemList);
}
GUILayout.EndHorizontal();
}
else
{
EditorGUILayout.HelpBox("Error", MessageType.Error);
}
GUILayout.EndVertical();
}
private void AddItem(List<vItem> items)
{
OrderByID(ref items);
for (int i = 0; i < items.Count; i++)
{
items[i] = Instantiate(items[i]);
items[i].name = items[i].name.Replace("(Clone)", string.Empty);
}
List<vItem> itemsWithSameID = new List<vItem>();
for (int i = 0; i < items.Count; i++)
{
for (int z = 0; z < i; z++)
{
var itemA = items[i];
var itemB = items[z];
if (itemA != itemB && itemA.id.Equals(itemB.id) && !itemsWithSameID.Contains(itemA))
{
itemsWithSameID.Add(itemA);
}
}
}
for (int i = 0; i < itemsWithSameID.Count; i++)
{
itemsWithSameID[i].id = GetUniqueID(items, itemsWithSameID[i].id);
}
OrderByID(ref items);
for (int i = 0; i < items.Count; i++)
{
AddItem(items[i]);
}
}
private void AddItem(vItem item)
{
if (item.name.Contains("(Clone)"))
{
item.name = item.name.Replace("(Clone)", string.Empty);
}
if (item && !itemList.items.Find(it => it.name.ToClearUpper().Equals(item.name.ToClearUpper())))
{
AssetDatabase.AddObjectToAsset(item, AssetDatabase.GetAssetPath(itemList));
item.hideFlags = HideFlags.HideInHierarchy;
if (itemList.items.Exists(it => it.id.Equals(item.id)))
item.id = GetUniqueID();
itemList.items.Add(item);
OrderByID(ref itemList.items);
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(itemList);
AssetDatabase.SaveAssets();
}
}
private void AddItemCreated()
{
AddItem(addItem);
addItem = null;
inAddItem = false;
addItemDrawer = null;
}
protected virtual void DuplicateItem(vItem targetItem)
{
addItem = Instantiate(targetItem);
AssetDatabase.AddObjectToAsset(addItem, AssetDatabase.GetAssetPath(itemList));
addItem.hideFlags = HideFlags.HideInHierarchy;
addItem.id = GetUniqueID();
itemList.items.Add(addItem);
OrderByID(ref itemList.items);
addItem = null;
inAddItem = false;
addItemDrawer = null;
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(itemList);
AssetDatabase.SaveAssets();
}
protected virtual int GetUniqueID(List<vItem> items, int value = 0)
{
var result = value;
for (int i = 0; i < items.Count + 1; i++)
{
var item = items.Find(t => t.id == i);
if (item == null)
{
result = i;
break;
}
}
return result;
}
protected virtual int GetUniqueID(int value = 0)
{
return GetUniqueID(itemList.items);
}
protected virtual void OrderByID(ref List<vItem> items)
{
if (items != null && items.Count > 0)
{
items = items.OrderBy(i => i.id).ToList();
}
}
}
}

View File

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

View File

@@ -0,0 +1,600 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Invector.vItemManager
{
[CustomEditor(typeof(vItemManager), true)]
[System.Serializable]
public class vItemManagerEditor : vEditorBase
{
#region Variables
protected vItemManager manager;
protected SerializedProperty itemReferenceList;
protected GUISkin oldSkin;
protected Vector2 scroll;
protected bool showManagerEvents;
protected bool[] inEdition;
protected string[] newPointNames;
protected Transform parentBone;
protected Animator animator;
protected Rect buttonRect;
protected SerializedProperty[] events;
#endregion
protected virtual string[] ignoreProperties => new string[] { "equipPoints", "applyAttributeEvents", "items", "startItems", "onStartItemUsage", "onUseItem", "onUseItemFail", "onAddItem", "onAddItemID", "onRemoveItemID", "onChangeItemAmount", "onDestroyItem", "onDropItem", "onOpenCloseInventory", "onEquipItem", "onUnequipItem", "onFinishEquipItem", "onFinishUnequipItem", "onSetLockedToEquip", "onSaveItems", "onLoadItems", "onCollectItem" };
protected override void OnEnable()
{
base.OnEnable();
m_Logo = (Texture2D)Resources.Load("itemManagerIcon", typeof(Texture2D));
manager = (vItemManager)target;
itemReferenceList = serializedObject.FindProperty("startItems");
skin = Resources.Load("vSkin") as GUISkin;
vItemManagerUtilities.CreateDefaultEquipPoints(manager);
animator = manager.GetComponent<Animator>();
if (manager.equipPoints != null)
{
inEdition = new bool[manager.equipPoints.Count];
newPointNames = new string[manager.equipPoints.Count];
}
else
{
manager.equipPoints = new List<EquipPoint>();
}
events = new SerializedProperty[]
{
serializedObject.FindProperty("onStartItemUsage"),
serializedObject.FindProperty("onUseItem"),
serializedObject.FindProperty("onUseItemFail"),
serializedObject.FindProperty("onAddItem"),
serializedObject.FindProperty("onAddItemID"),
serializedObject.FindProperty("onRemoveItemID"),
serializedObject.FindProperty("onChangeItemAmount"),
serializedObject.FindProperty("onDestroyItem"),
serializedObject.FindProperty("onDropItem"),
serializedObject.FindProperty("onOpenCloseInventory"),
serializedObject.FindProperty("onEquipItem"),
serializedObject.FindProperty("onUnequipItem"),
serializedObject.FindProperty("onFinishEquipItem"),
serializedObject.FindProperty("onFinishUnequipItem"),
serializedObject.FindProperty("onSetLockedToEquip"),
serializedObject.FindProperty("onSaveItems"),
serializedObject.FindProperty("onLoadItems"),
serializedObject.FindProperty("onCollectItem"),
};
}
public override void OnInspectorGUI()
{
oldSkin = GUI.skin;
serializedObject.Update();
if (skin)
{
GUI.skin = skin;
}
GUILayout.BeginVertical("ITEM MANAGER", "window");
GUILayout.Label(m_Logo, GUILayout.MaxHeight(25));
openCloseWindow = GUILayout.Toggle(openCloseWindow, openCloseWindow ? "Close" : "Open", EditorStyles.toolbarButton);
if (openCloseWindow)
{
GUI.skin = oldSkin;
DrawPropertiesExcluding(serializedObject, ignoreProperties.Append(ignore_vMono));
GUI.skin = skin;
GUI.enabled = Application.isPlaying && ((vItemManager)target).GetItems().Count > 0;
GUILayout.BeginHorizontal("box");
if (GUILayout.Button("Drop All Items"))
{
((vItemManager)target).DropAllItens();
}
if (GUILayout.Button("Destroy All Items"))
{
((vItemManager)target).DestroyAllItems();
}
GUILayout.EndHorizontal();
GUI.enabled = true;
if (GUILayout.Button("Open Item List"))
{
ShowItemListWindow();
}
if (manager.itemListData)
{
GUILayout.BeginVertical("box");
//if (itemReferenceList.arraySize > manager.itemListData.items.Count)
//{
// manager.startItems.Resize(manager.itemListData.items.Count);
//}
GUILayout.Box("Start Items " + manager.startItems.Count);
if (GUILayout.Button("Add Item", EditorStyles.miniButton))
{
PopupWindow.Show(buttonRect, new vItemSelector
(manager.itemListData.items, ref manager.itemsFilter,
(vItem item) =>//OnSelectItem
{
itemReferenceList.arraySize++;
itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("id").intValue = item.id;
itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("amount").intValue = 1;
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
}
));
}
if (Event.current.type == EventType.Repaint)
{
buttonRect = GUILayoutUtility.GetLastRect();
}
GUIStyle boxStyle = new GUIStyle(GUI.skin.box);
scroll = GUILayout.BeginScrollView(scroll, GUILayout.MinHeight(200), GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
try
{
for (int i = 0; i < manager.startItems.Count; i++)
{
var item = manager.itemListData.items.Find(t => t.id.Equals(manager.startItems[i].id));
if (item)
{
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
GUILayout.BeginHorizontal();
var rect = GUILayoutUtility.GetRect(50, 50);
if (item.icon != null)
{
DrawTextureGUI(rect, item.icon, new Vector2(50, 50));
}
var name = " ID " + item.id.ToString("00") + "\n - " + item.name + "\n - " + item.type.ToString();
var content = new GUIContent(name, null, "Click to Open");
GUILayout.Label(content, EditorStyles.miniLabel);
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
GUILayout.Label("Add to EquipArea", EditorStyles.miniLabel);
manager.startItems[i].addToEquipArea = EditorGUILayout.Toggle("", manager.startItems[i].addToEquipArea, GUILayout.Width(30));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (manager.startItems[i].addToEquipArea)
{
GUILayout.Label("EquipArea", EditorStyles.miniLabel);
manager.startItems[i].indexArea = EditorGUILayout.IntField("", manager.startItems[i].indexArea, GUILayout.Width(30));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (manager.startItems[i].addToEquipArea)
{
GUILayout.Label("AutoEquip", EditorStyles.miniLabel);
manager.startItems[i].autoEquip = EditorGUILayout.Toggle("", manager.startItems[i].autoEquip, GUILayout.Width(30));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Amount", EditorStyles.miniLabel);
manager.startItems[i].amount = EditorGUILayout.IntField(manager.startItems[i].amount, GUILayout.Width(30));
if (manager.startItems[i].amount < 1)
{
manager.startItems[i].amount = 1;
}
GUILayout.EndHorizontal();
if (item.attributes.Count > 0)
{
manager.startItems[i].changeAttributes = GUILayout.Toggle(manager.startItems[i].changeAttributes, new GUIContent("Change Attributes", "This is a override of the original item attributes"), EditorStyles.miniButton, GUILayout.ExpandWidth(true));
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
if (GUILayout.Button("x", GUILayout.Width(25), GUILayout.Height(25)))
{
itemReferenceList.DeleteArrayElementAtIndex(i);
EditorUtility.SetDirty(target);
serializedObject.ApplyModifiedProperties();
break;
}
GUILayout.EndHorizontal();
Color backgroundColor = GUI.backgroundColor;
GUI.backgroundColor = Color.clear;
var _rec = GUILayoutUtility.GetLastRect();
_rec.width -= 100;
EditorGUIUtility.AddCursorRect(_rec, MouseCursor.Link);
if (GUI.Button(_rec, ""))
{
ShowItemListWindow(item);
}
GUILayout.Space(7);
GUI.backgroundColor = backgroundColor;
if (item.attributes != null && item.attributes.Count > 0)
{
if (manager.startItems[i].changeAttributes)
{
if (GUILayout.Button("Reset", EditorStyles.miniButton))
{
manager.startItems[i].attributes = null;
}
if (manager.startItems[i].attributes == null)
{
manager.startItems[i].attributes = item.attributes.CopyAsNew();
}
else if (manager.startItems[i].attributes.Count != item.attributes.Count)
{
manager.startItems[i].attributes = item.attributes.CopyAsNew();
}
else
{
for (int a = 0; a < manager.startItems[i].attributes.Count; a++)
{
GUILayout.BeginHorizontal();
GUILayout.Label(manager.startItems[i].attributes[a].name.ToString());
manager.startItems[i].attributes[a].value = EditorGUILayout.IntField(manager.startItems[i].attributes[a].value, GUILayout.MaxWidth(60));
GUILayout.EndHorizontal();
}
}
}
}
GUILayout.EndVertical();
}
else
{
itemReferenceList.DeleteArrayElementAtIndex(i);
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
break;
}
}
}
catch
{
}
GUILayout.EndScrollView();
GUI.skin.box = boxStyle;
GUILayout.EndVertical();
if (GUI.changed)
{
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
}
}
var equipPoints = serializedObject.FindProperty("equipPoints");
var applyAttributeEvents = serializedObject.FindProperty("applyAttributeEvents");
if (equipPoints.arraySize != inEdition.Length)
{
inEdition = new bool[equipPoints.arraySize];
newPointNames = new string[manager.equipPoints.Count];
}
if (equipPoints != null)
{
DrawEquipPoints(equipPoints);
}
if (applyAttributeEvents != null)
{
DrawAttributeEvents(applyAttributeEvents);
}
GUILayout.BeginVertical("box");
showManagerEvents = GUILayout.Toggle(showManagerEvents, showManagerEvents ? "Close Events" : "Open Events", EditorStyles.miniButton);
GUI.skin = oldSkin;
if (showManagerEvents)
{
for (int i = 0; i < events.Length; i++)
{
if (events[i] != null) EditorGUILayout.PropertyField(events[i]);
}
}
GUI.skin = skin;
GUILayout.EndVertical();
}
GUILayout.EndVertical();
if (GUI.changed)
{
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
}
GUI.skin = oldSkin;
}
protected virtual void ShowItemListWindow(vItem item = null)
{
if (item == null)
{
vItemListWindow.CreateWindow(manager.itemListData);
}
else if (manager.itemListData.inEdition)
{
if (vItemListWindow.Instance == null)
{
vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item));
}
}
else
{
vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item));
}
if (item)
{
vItemListWindow.SetCurrentSelectedItem(manager.itemListData.items.IndexOf(item));
}
}
protected virtual void DrawTextureGUI(Rect position, Sprite sprite, Vector2 size)
{
Rect spriteRect = new Rect(sprite.rect.x / sprite.texture.width, sprite.rect.y / sprite.texture.height,
sprite.rect.width / sprite.texture.width, sprite.rect.height / sprite.texture.height);
Vector2 actualSize = size;
actualSize.y *= (sprite.rect.height / sprite.rect.width);
GUI.DrawTextureWithTexCoords(new Rect(position.x, position.y + (size.y - actualSize.y) / 2, actualSize.x, actualSize.y), sprite.texture, spriteRect);
}
protected virtual GUIContent GetItemContent(vItem item)
{
var texture = item.icon != null ? item.icon.texture : null;
return new GUIContent(item.name, texture, item.description);
}
protected virtual List<vItem> GetItemByFilter(List<vItem> items, List<vItemType> filter)
{
return items.FindAll(i => filter.Contains(i.type));
}
protected virtual GUIContent[] GetItemContents(List<vItem> items)
{
GUIContent[] names = new GUIContent[items.Count];
for (int i = 0; i < items.Count; i++)
{
var texture = items[i].icon != null ? items[i].icon.texture : null;
names[i] = new GUIContent(items[i].name, texture, items[i].description);
}
return names;
}
protected virtual void DrawEquipPoints(SerializedProperty prop)
{
GUILayout.BeginVertical("box");
prop.isExpanded = GUILayout.Toggle(prop.isExpanded, prop.isExpanded ? "Close Equip Points" : "Open Equip Points", EditorStyles.miniButton);
if (prop.isExpanded)
{
prop.arraySize = EditorGUILayout.IntField("Points", prop.arraySize);
for (int i = 0; i < prop.arraySize; i++)
{
var handler = prop.GetArrayElementAtIndex(i).FindPropertyRelative("handler");
var equipPointName = prop.GetArrayElementAtIndex(i).FindPropertyRelative("equipPointName");
var defaultPoint = handler.FindPropertyRelative("defaultHandler");
var points = handler.FindPropertyRelative("customHandlers");
var onInstantiateEquiment = prop.GetArrayElementAtIndex(i).FindPropertyRelative("onInstantiateEquiment");
try
{
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(equipPointName);
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(20)))
{
prop.DeleteArrayElementAtIndex(i);
GUILayout.EndHorizontal();
break;
}
GUILayout.EndHorizontal();
EditorGUILayout.PropertyField(defaultPoint);
GUILayout.BeginVertical("box");
points.isExpanded = GUILayout.Toggle(points.isExpanded, "Custom Handles", EditorStyles.miniButton);
if (points.isExpanded)
{
GUILayout.Space(5);
GUILayout.BeginHorizontal();
if (!inEdition[i] && GUILayout.Button("New Handler", EditorStyles.miniButton))
{
inEdition[i] = true;
if (equipPointName.stringValue.Contains("Left") || equipPointName.stringValue.Contains("left"))
{
if (animator)
{
parentBone = animator.GetBoneTransform(HumanBodyBones.LeftHand);
}
}
else
{
if (animator)
{
parentBone = animator.GetBoneTransform(HumanBodyBones.RightHand);
}
}
}
if (!inEdition[i] && GUILayout.Button("Add Handler", EditorStyles.miniButton))
{
//points.arraySize++;
Undo.RecordObject(manager, "Insert Point");
points.InsertArrayElementAtIndex(points.arraySize);
points.GetArrayElementAtIndex(points.arraySize - 1).objectReferenceValue = null;
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
}
GUILayout.EndHorizontal();
if (inEdition[i])
{
GUILayout.Box("New Custom Handler");
parentBone = (Transform)EditorGUILayout.ObjectField("Parent Bone", parentBone, typeof(Transform), true);
newPointNames[i] = EditorGUILayout.TextField("Custom Handler Name", newPointNames[i]);
bool valid = true;
if (string.IsNullOrEmpty(newPointNames[i]))
{
valid = false;
EditorGUILayout.HelpBox("Custom Handler Name is empty", MessageType.Error);
}
var array = ConvertToArray<Transform>(points);
if (Array.Exists<Transform>(array, point => point.gameObject.name.Equals(newPointNames[i])))
{
valid = false;
EditorGUILayout.HelpBox("Custom Handler Name already exist", MessageType.Error);
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Cancel", EditorStyles.miniButton))
{
inEdition[i] = false;
}
GUI.enabled = parentBone && valid;
if (GUILayout.Button("Create", EditorStyles.miniButton))
{
var customPoint = new GameObject(newPointNames[i]);
customPoint.transform.parent = parentBone;
customPoint.transform.localPosition = Vector3.zero;
customPoint.transform.forward = manager.transform.forward;
points.arraySize++;
points.GetArrayElementAtIndex(points.arraySize - 1).objectReferenceValue = customPoint.transform;
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
inEdition[i] = false;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
GUILayout.Space(5);
for (int a = 0; a < points.arraySize; a++)
{
var remove = false;
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(points.GetArrayElementAtIndex(a), true);
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(20)))
{
remove = true;
}
GUILayout.EndHorizontal();
if (remove)
{
Undo.RecordObject(manager, "Delete Point");
var obj = (Transform)points.GetArrayElementAtIndex(a).objectReferenceValue;
if (obj)
{
points.GetArrayElementAtIndex(a).objectReferenceValue = null;
//points.DeleteArrayElementAtIndex(a);
//DestroyImmediate(obj.gameObject);
}
points.DeleteArrayElementAtIndex(a);
EditorUtility.SetDirty(manager);
serializedObject.ApplyModifiedProperties();
break;
}
}
}
var _array = ConvertToArray<Transform>(points);
bool _valid = true;
for (int a = 0; a < _array.Length; a++)
{
if (_array[a] != null)
{
var name = _array[a].gameObject.name;
if (Array.FindAll<Transform>(_array, point => point != null && point.gameObject.name.Equals(name)).Length > 1)
{
_valid = false;
}
}
}
if (_valid == false)
{
EditorGUILayout.HelpBox("You can't use two handles with the same name", MessageType.Error);
}
GUILayout.EndVertical();
GUI.skin = oldSkin;
if (onInstantiateEquiment != null)
{
EditorGUILayout.PropertyField(onInstantiateEquiment);
}
GUI.skin = skin;
GUILayout.EndVertical();
}
catch { }
}
}
GUILayout.EndVertical();
}
protected virtual T[] ConvertToArray<T>(SerializedProperty prop)
{
T[] value = new T[prop.arraySize];
for (int i = 0; i < prop.arraySize; i++)
{
object element = prop.GetArrayElementAtIndex(i).objectReferenceValue;
value[i] = (T)element;
}
return value;
}
protected virtual void DrawAttributeEvents(SerializedProperty prop)
{
GUILayout.BeginVertical("box");
prop.isExpanded = GUILayout.Toggle(prop.isExpanded, prop.isExpanded ? "Close Attribute Events" : "Open Attribute Events", EditorStyles.miniButton);
if (prop.isExpanded)
{
prop.arraySize = EditorGUILayout.IntField("Attributes", prop.arraySize);
for (int i = 0; i < prop.arraySize; i++)
{
var attributeName = prop.GetArrayElementAtIndex(i).FindPropertyRelative("attribute");
var onApplyAttribute = prop.GetArrayElementAtIndex(i).FindPropertyRelative("onApplyAttribute");
try
{
GUILayout.BeginVertical("box");
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(attributeName);
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(20)))
{
prop.DeleteArrayElementAtIndex(i);
GUILayout.EndHorizontal();
break;
}
GUILayout.EndHorizontal();
GUI.skin = oldSkin;
EditorGUILayout.PropertyField(onApplyAttribute);
GUI.skin = skin;
GUILayout.EndVertical();
}
catch { }
}
}
GUILayout.EndVertical();
}
}
}

View File

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

View File

@@ -0,0 +1,37 @@
using UnityEngine;
using System.Collections.Generic;
namespace Invector.vItemManager
{
public static class vItemManagerUtilities
{
public static void CreateDefaultEquipPoints(vItemManager itemManager)
{
var animator = itemManager.GetComponent<Animator>();
if (itemManager.equipPoints == null)
itemManager.equipPoints = new List<EquipPoint>();
#region LeftEquipPoint
var equipPointL = itemManager.equipPoints.Find(p => p.equipPointName == "LeftArm");
if (equipPointL == null)
{
EquipPoint pointL = new EquipPoint();
pointL.equipPointName = "LeftArm";
itemManager.equipPoints.Add(pointL);
}
#endregion
#region RightEquipPoint
var equipPointR = itemManager.equipPoints.Find(p => p.equipPointName == "RightArm");
if (equipPointR == null)
{
EquipPoint pointR = new EquipPoint();
pointR.equipPointName = "RightArm";
itemManager.equipPoints.Add(pointR);
}
#endregion
}
}
}

View File

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

View File

@@ -0,0 +1,98 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Invector.vItemManager
{
public class vItemSelector : PopupWindowContent
{
public UnityEngine.Events.UnityAction<vItem> onSelect;
public List<vItem> items;
public GUIContent[] contents;
GUIStyle boxStyle;
public List<vItemType> filter = new List<vItemType>();
public string search = "";
bool isOpenFilter;
Vector2 scroll;
public override Vector2 GetWindowSize()
{
return new Vector2(200, Mathf.Clamp(items.Count * 50, 50, 500));
}
public vItemSelector(List<vItem> items,ref List<vItemType> filter, UnityEngine.Events.UnityAction<vItem> onSelect)
{
this.items = items;
this.filter = filter;
this.onSelect = onSelect; CreateContent();
}
void CreateContent()
{
boxStyle = new GUIStyle(GUI.skin.box);
boxStyle.alignment = TextAnchor.UpperLeft;
boxStyle.fontStyle = FontStyle.Italic;
boxStyle.fontSize = 11;
contents = new GUIContent[items.Count];
for (int i = 0; i < items.Count; i++)
{
var name = " ID " + items[i].id.ToString("00") + "\n - " + items[i].name + "\n - " + items[i].type.ToString();
var texture = items[i].iconTexture;
var tooltip = items[i].description;
contents[i] = new GUIContent(name, texture, tooltip);
}
}
public override void OnGUI(Rect rect)
{
if (contents == null) return;
GUILayout.Label("ItemSelector", EditorStyles.boldLabel);
DrawFilter();
scroll = GUILayout.BeginScrollView(scroll, "box");
for (int i = 0; i < contents.Length; i++)
{
if ((filter.Count == 0 || filter.Contains(items[i].type)) && (string.IsNullOrEmpty(search) || items[i].name.ToLower().Contains(search.ToLower())))
if (GUILayout.Button(contents[i], boxStyle, GUILayout.Height(50), GUILayout.MinWidth(50)))
{
onSelect(items[i]);
editorWindow.Close();
}
}
GUILayout.EndScrollView();
}
void DrawFilter()
{
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
isOpenFilter = EditorGUILayout.Foldout(isOpenFilter, "Filters (" + filter.Count + ")");
if (GUILayout.Button("+", GUILayout.Width(20), GUILayout.Height(15)))
{
isOpenFilter = true;
filter.Add((vItemType)0);
}
GUILayout.EndHorizontal();
if (isOpenFilter)
{
for (int i = 0; i < filter.Count; i++)
{
GUILayout.BeginHorizontal();
filter[i] = (vItemType)EditorGUILayout.EnumPopup(filter[i]);
if (GUILayout.Button("-", GUILayout.Width(20), GUILayout.Height(15)))
{
filter.RemoveAt(i);
GUILayout.EndHorizontal();
break;
}
GUILayout.EndHorizontal();
}
}
GUILayout.EndVertical();
GUILayout.BeginHorizontal();
search = GUILayout.TextField(search, GUILayout.Width(170));
GUILayout.Label(EditorGUIUtility.IconContent("Search Icon"), GUILayout.Height(20));
GUILayout.EndHorizontal();
}
}
}

View File

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

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 6c9da845e2ca25045ae62dd6c5f90050
folderAsset: yes
timeCreated: 1497300483
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,115 @@
using UnityEngine;
namespace Invector.vItemManager
{
[vClassHeader("Use Item Event Trigger", useHelpBox = true, helpBoxText = "This script enable ItemUsage when TriggerEnter and disable onTriggerExit", openClose = false)]
public class UseItemEventTrigger : vMonoBehaviour
{
/// <summary>
/// Item usage Event
/// </summary>
public OnUseItemEvent itemEvent;
protected vItemManager itemManager;
/// <summary>
/// Item usage Event class
/// </summary>
[System.Serializable]
public class OnUseItemEvent
{
internal vItem targetItem;
public int id;
[vHelpBox("Check this to enable the menu UI Button 'Use' on the Inventory Window")]
public bool canUseWithOpenInventory;
[vHelpBox("Override the Delay to use this Item")]
public bool overrideItemUsageDelay;
[vHideInInspector("overrideItemUsageDelay")]
public float newDeleyTime;
internal float defaultDelay;
public UnityEngine.Events.UnityEvent onUse;
/// <summary>
/// Event called when the inventory is opened or closed while in trigger
/// </summary>
/// <param name="value"></param>
public void OnOpenInventory(bool value)
{
if (canUseWithOpenInventory || !targetItem) return;
targetItem.canBeUsed = !value;
}
/// <summary>
/// Change item usage delay time, called when the Player with an Item Manager enters a trigger
/// </summary>
public void ChangeItemUsageDelay()
{
if (!overrideItemUsageDelay || targetItem == null) return;
defaultDelay = targetItem.enableDelayTime;
targetItem.enableDelayTime = newDeleyTime;
}
/// <summary>
/// Reset item usage delay time, called when the Player with an Item Manager exit a trigger
/// </summary>
public void ResetItemUsageDelay()
{
if (!overrideItemUsageDelay || targetItem == null) return;
targetItem.enableDelayTime = defaultDelay;
}
}
public virtual void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
itemManager = other.GetComponent<vItemManager>();
if (itemManager)
{
itemEvent.targetItem = itemManager.GetItem(itemEvent.id);
if (itemEvent.targetItem)
{
itemEvent.ChangeItemUsageDelay();
itemManager.onUseItem.AddListener(OnUseItem);
itemManager.onOpenCloseInventory.AddListener(itemEvent.OnOpenInventory);
itemEvent.targetItem.canBeUsed = true;
}
}
}
}
/// <summary>
/// Event called when the Player with Item Manager use an item while in a trigger
/// </summary>
/// <param name="item"></param>
protected virtual void OnUseItem(vItem item)
{
if (itemManager && itemEvent.id == item.id)
{
itemManager.inventory.CloseInventory();
itemManager.onUseItem.RemoveListener(OnUseItem);
itemManager.onOpenCloseInventory.RemoveListener(itemEvent.OnOpenInventory);
itemEvent.onUse.Invoke();
itemEvent.ResetItemUsageDelay();
itemEvent.targetItem = null;
}
}
public virtual void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
if (itemManager)
{
itemManager.onUseItem.RemoveListener(OnUseItem);
itemManager.onOpenCloseInventory.RemoveListener(itemEvent.OnOpenInventory);
if (itemEvent.targetItem)
{
itemEvent.targetItem.canBeUsed = false;
itemEvent.ResetItemUsageDelay();
itemEvent.targetItem = null;
}
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,40 @@
using UnityEngine;
namespace Invector.vItemManager
{
[vClassHeader("Add Item By ID", "This is a simple example on how to add items using script", openClose = false)]
public class vAddItemByID : vMonoBehaviour
{
public int id, amount;
public bool addToEquipArea=true;
[vHideInInspector("addToEquipArea")]
public bool autoEquip;
public bool destroyAfter;
[vHideInInspector("addToEquipArea")]
public int indexOfEquipArea;
/// <summary>
/// Simple example on how to add one or more items into the inventory using code
/// You can also auto equip the item if it's a MeleeWeapon Type
/// </summary>
/// <param name="other"></param>
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
var itemManager = other.gameObject.GetComponent<vItemManager>();
if (itemManager)
{
var reference = new ItemReference(id);
reference.amount = amount;
reference.addToEquipArea = addToEquipArea;
reference.autoEquip = autoEquip;
reference.indexArea = indexOfEquipArea;
itemManager.CollectItem(reference,textDelay:2f,ignoreItemAnimation:false);
if (destroyAfter) Destroy(gameObject);
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,75 @@
using System.Collections.Generic;
namespace Invector.vItemManager
{
using vCharacterController;
[vClassHeader("Check if can Add Health", "Simple Example to verify if the health item can be used based on the character's health is full or not.", openClose = false)]
public class vCheckCanAddHealth : vMonoBehaviour
{
public vItemManager itemManager;
public vThirdPersonController tpController;
public bool getInParent = true;
protected bool canUse;
protected bool firstRun;
protected virtual void Start()
{
// first we need to access our itemManager from the Controller
if (itemManager == null)
{
//check 'getInParent' if this script is attached to a children of the itemManager
if (getInParent)
itemManager = GetComponentInParent<vItemManager>();
else
itemManager = GetComponent<vItemManager>();
}
// now we access the Controller itself to know the currentHealth later
if (tpController == null)
{
if (getInParent)
tpController = GetComponentInParent<vThirdPersonController>();
else
tpController = GetComponent<vThirdPersonController>();
}
// if a itemManager is founded, we use this event to call our CanUseItem method
if (itemManager)
{
itemManager.canUseItemDelegate -= new vItemManager.CanUseItemDelegate(CanUseItem);
itemManager.canUseItemDelegate += new vItemManager.CanUseItemDelegate(CanUseItem);
}
}
protected virtual void OnDestroy()
{
var itemManager = GetComponent<vItemManager>();
if (itemManager)
// remove the event when this gameObject is destroyed
itemManager.canUseItemDelegate -= new vItemManager.CanUseItemDelegate(CanUseItem);
}
protected virtual void CanUseItem(vItem item, ref List<bool> validateResult)
{
// search for the attribute 'Health'
if (item.GetItemAttribute(vItemAttributes.Health) != null)
{
// the variable valid will identify if the currentHealth is lower than the maxHealth, allowing to use the item
var valid = tpController.currentHealth < tpController.maxHealth;
if (valid != canUse || !firstRun)
{
canUse = valid;
firstRun = true;
// trigger a custom text if there is a HUDController in the scene
vHUDController.instance.ShowText(valid ? "Increase health" : "Can't use " + item.name + " because your health is full", 4f);
}
if (!valid)
validateResult.Add(valid);
}
}
}
}

View File

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

View File

@@ -0,0 +1,92 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Invector.vItemManager
{
[vClassHeader("Check Item in Inventory", openClose = false)]
public class vCheckItemInInventory : vMonoBehaviour
{
protected vItemManager itemManager;
public bool getInParent = true;
public List<CheckItemIDEvent> itemIDEvents;
void Awake()
{
if (!itemManager)
{
if (getInParent)
itemManager = GetComponentInParent<vItemManager>();
else
itemManager = GetComponent<vItemManager>();
if (itemManager)
{
itemManager.onAddItemID.AddListener(CheckItemExists);
itemManager.onRemoveItemID.AddListener(CheckItemExists);
}
}
}
public void CheckOnTrigger(Collider collider)
{
if (collider != null)
{
itemManager = collider.gameObject.GetComponent<vItemManager>();
if (itemManager)
{
for (int i = 0; i < itemIDEvents.Count; i++)
{
CheckItemIDEvent check = itemIDEvents[i];
CheckItemID(check);
}
}
}
}
private void CheckItemExists(int arg1)
{
for (int i = 0; i < itemIDEvents.Count; i++)
{
CheckItemIDEvent check = itemIDEvents[i];
CheckItemID(check);
}
}
private void CheckItemID(CheckItemIDEvent check)
{
if (check.Check(itemManager))
{
check.onContainItem.Invoke();
}
else
{
check.onNotContainItem.Invoke();
}
}
[System.Serializable]
public class CheckItemIDEvent
{
public string name;
public List<int> _itemsID;
public UnityEvent onContainItem, onNotContainItem;
public bool Check(vItemManager itemManager)
{
bool _ContainItem = true;
for (int i = 0; i < _itemsID.Count; i++)
{
if (!itemManager.ContainItem(_itemsID[i]))
{
_ContainItem = false;
break;
}
}
return _ContainItem;
}
}
}
}

View File

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

View File

@@ -0,0 +1,88 @@
using System.Collections.Generic;
using UnityEngine.Serialization;
namespace Invector.vItemManager
{
[vClassHeader("Check If Item Is Equipped", openClose = false)]
public class vCheckItemIsEquipped : vMonoBehaviour
{
public vItemManager itemManager;
public bool getInParent = true;
[FormerlySerializedAs("itemChecks")]
public List<CheckItemIDEvent> itemIDEvents;
public List<CheckItemTypeEvent> itemTypeEvents;
void Awake()
{
if (!itemManager)
{
if (getInParent)
itemManager = GetComponentInParent<vItemManager>();
else
itemManager = GetComponent<vItemManager>();
itemManager.onEquipItem.AddListener(CheckIsEquipped);
itemManager.onUnequipItem.AddListener(CheckIsEquipped);
}
}
private void CheckIsEquipped(vEquipArea arg0, vItem arg1)
{
for (int i = 0; i < itemIDEvents.Count; i++)
{
CheckItemIDEvent check = itemIDEvents[i];
CheckItemID(check);
}
for (int i = 0; i < itemTypeEvents.Count; i++)
{
CheckItemTypeEvent check = itemTypeEvents[i];
CheckItemType(check);
}
}
private void CheckItemID(CheckItemIDEvent check)
{
bool _isEquipped = check._itemsID.Exists(t => itemManager.ItemIsEquipped(t));
if (_isEquipped != check.isEquipped)
{
check.isEquipped = _isEquipped;
if (check.isEquipped)
check.onIsItemEquipped.Invoke();
else
check.onIsItemUnequipped.Invoke();
}
}
private void CheckItemType(CheckItemTypeEvent check)
{
bool _isEquipped = check.itemTypes.Exists(t => itemManager.ItemTypeIsEquipped(t));
if (_isEquipped != check.isEquipped)
{
check.isEquipped = _isEquipped;
if (check.isEquipped)
check.onIsItemEquipped.Invoke();
else
check.onIsItemUnequipped.Invoke();
}
}
[System.Serializable]
public class CheckItemIDEvent
{
public string name;
public List<int> _itemsID;
public UnityEngine.Events.UnityEvent onIsItemEquipped, onIsItemUnequipped;
internal bool isEquipped;
}
[System.Serializable]
public class CheckItemTypeEvent
{
public string name;
public List<vItemType> itemTypes;
public UnityEngine.Events.UnityEvent onIsItemEquipped, onIsItemUnequipped;
internal bool isEquipped;
}
}
}

View File

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

View File

@@ -0,0 +1,95 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Invector.vItemManager
{
[vClassHeader("Check Items in Inventory", openClose = false)]
public class vCheckItemsInInventory : vMonoBehaviour
{
public vItemManager itemManager;
public List<CheckItemIDEvent> itemIDEvents;
IEnumerator Start()
{
yield return new WaitForEndOfFrame();
if (itemManager)
{
itemManager.inventory.OnUpdateInventory += (CheckItemExists);
}
}
private void OnValidate()
{
if (!itemManager)
{
itemManager = GetComponent<vItemManager>();
if (!itemManager)
{
itemManager = GetComponentInParent<vItemManager>();
}
}
}
public void CheckItemExists()
{
for (int i = 0; i < itemIDEvents.Count; i++)
{
CheckItemIDEvent check = itemIDEvents[i];
CheckItemID(check);
}
}
private void CheckItemID(CheckItemIDEvent check)
{
if (check.Check(itemManager))
{
check.onContainItem.Invoke();
}
else
{
check.onNotContainItem.Invoke();
}
}
[System.Serializable]
public class CheckItemIDEvent
{
public string name;
public List<ItemID> itemIds;
public UnityEvent onContainItem, onNotContainItem;
public bool Check(vItemManager itemManager)
{
bool _ContainItem = true;
for (int i = 0; i < itemIds.Count; i++)
{
ItemID itemID = itemIds[i];
if (itemID.verifyAmmount && itemManager.GetAllAmount(itemID.id) < itemID.ammount)
{
_ContainItem = false;
break;
}
else if (!itemID.verifyAmmount && !itemManager.ContainItem(itemID.id))
{
_ContainItem = false;
break;
}
}
return _ContainItem;
}
}
[System.Serializable]
public class ItemID
{
public int id;
public bool verifyAmmount;
public int ammount;
}
}
}

View File

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

View File

@@ -0,0 +1,106 @@
using UnityEngine;
namespace Invector.vItemManager
{
[vClassHeader("Contains Item Trigger", "Simple trigger to check if the Player has a specific Item, you can also use Events to trigger something if you have the item.", openClose = false)]
public class vContainsItemTrigger : vMonoBehaviour
{
public bool getItemByName;
[vHideInInspector("getItemByName")]
public string itemName;
[vHideInInspector("getItemByName", true)]
public int itemID;
public bool useTriggerStay;
public int desiredAmount = 1;
[Header("OnTriggerEnter/Stay")]
public UnityEngine.Events.UnityEvent onContains;
public UnityEngine.Events.UnityEvent onNotContains;
[Header("OnTriggerExit")]
public UnityEngine.Events.UnityEvent onExit;
public vItemManager itemManager;
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
var itemManager = other.GetComponent<vItemManager>();
if (itemManager)
{
CheckItem(itemManager);
}
}
}
public void OnTriggerStay(Collider other)
{
if (!useTriggerStay) return;
if (other.gameObject.CompareTag("Player"))
{
itemManager = other.GetComponent<vItemManager>();
if (itemManager)
{
CheckItem(itemManager);
}
}
}
public void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
onExit.Invoke();
}
}
/// <summary>
/// Remove desired item of the target <seealso cref="vItemManager"/>
/// </summary>
public void RemoveDesiredItem()
{
if (itemManager)
{
if (getItemByName)
{
if (ContainsItem(itemManager))
{
itemManager.DestroyItem(itemManager.GetItem(itemName), desiredAmount > 1 ? desiredAmount : 1);
}
}
else
{
if (ContainsItem(itemManager))
{
itemManager.DestroyItem(itemManager.GetItem(itemID), desiredAmount > 1 ? desiredAmount : 1);
}
}
}
}
/// <summary>
/// Check if the <seealso cref="vItemManager"/> has the target item and call events <seealso cref="onContains"/> or <seealso cref="onNotContains"/>
/// </summary>
/// <param name="itemManager"></param>
protected virtual void CheckItem(vItemManager itemManager)
{
if (itemManager == null) return;
if (ContainsItem(itemManager))
{
onContains.Invoke();
}
else
onNotContains.Invoke();
}
/// <summary>
/// Check if a item exists in the <seealso cref="itemManager"/>
/// </summary>
/// <param name="itemManager"></param>
/// <returns>Contains or not</returns>
protected bool ContainsItem(vItemManager itemManager)
{
return desiredAmount > 1 ? (getItemByName ? itemManager.ContainItem(itemName, desiredAmount) : itemManager.ContainItem(itemID, desiredAmount)) :
(getItemByName ? itemManager.ContainItem(itemName) : itemManager.ContainItem(itemID));
}
}
}

View File

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

View File

@@ -0,0 +1,41 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Invector.vItemManager;
using UnityEngine;
using UnityEngine.Events;
public class vEquipItemTrigger : MonoBehaviour
{
public int itemID;
public UnityEvent OnEquipSuccess, OnEquipFail;
public vItemManager itemManager;
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
var itemManager = other.GetComponent<vItemManager>();
if (itemManager)
{
EquipItemIfExist(itemManager);
}
}
}
private void EquipItemIfExist(vItemManager itemManager)
{
if (itemManager.items.Exists(i => i.id == itemID))
{
var item = itemManager.items.Find(i => i.id == itemID);
var indexOfArea = System.Array.FindIndex(itemManager.inventory.equipAreas, area => area.equipSlots.Exists(slot => slot.itemType.Contains(item.type)));
itemManager.EquipItemToCurrentEquipSlot(item, indexOfArea);
OnEquipSuccess.Invoke();
}
else
{
OnEquipFail.Invoke();
}
}
}

View File

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

View File

@@ -0,0 +1,27 @@
using Invector;
using Invector.vItemManager;
using System.Collections;
using UnityEngine;
public class vLoadInventoryItemsExample : MonoBehaviour
{
vGameController gm;
void Start()
{
gm = GetComponent<vGameController>();
}
public void LoadItemsToInventory()
{
if (!gm) return;
StartCoroutine(LoadItems());
}
IEnumerator LoadItems()
{
yield return new WaitForSeconds(.1f);
var loadItems = gm.currentPlayer.GetComponent<vItemManager>();
loadItems.LoadItemsExample();
}
}

View File

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

View File

@@ -0,0 +1,40 @@
using UnityEngine;
using UnityEngine.Events;
namespace Invector.vItemManager
{
[vClassHeader("Remove Current Item", false)]
public class vRemoveCurrentItem : vMonoBehaviour
{
public enum Type
{
UnequipItem,
DestroyItem,
DropItem
}
public Type type = Type.UnequipItem;
[Tooltip("Immediately equip the item ignoring the Equip animation")]
public bool immediate = true;
[Tooltip("Equip Area of your Inventory Prefab")]
public int equipArea;
public UnityEvent OnTriggerEnterEvent;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
var itemManager = other.gameObject.GetComponent<vItemManager>();
if (itemManager)
{
if (type == Type.UnequipItem)
itemManager.UnequipCurrentEquipedItem(equipArea, immediate);
else if (type == Type.DestroyItem)
itemManager.DestroyCurrentEquipedItem(equipArea, immediate);
else
itemManager.DropCurrentEquippedItem(equipArea, immediate);
}
OnTriggerEnterEvent.Invoke();
}
}
}
}

View File

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

View File

@@ -0,0 +1,86 @@
using UnityEngine;
namespace Invector.vItemManager
{
[vClassHeader("Remove Item", openClose = false)]
public class vRemoveItem : vMonoBehaviour
{
public vRemoveCurrentItem.Type type = vRemoveCurrentItem.Type.DestroyItem;
public bool getItemByName;
[vHideInInspector("getItemByName")]
public string itemName;
[vHideInInspector("getItemByName", true)]
public int itemID;
/// <summary>
/// Remove item of the target collider
/// </summary>
/// <param name="target">target </param>
public void RemoveItem(Collider target)
{
var itemManager = target.GetComponent<vItemManager>();
RemoveItem(itemManager);
}
/// <summary>
/// Remove item of the target gameObject
/// </summary>
/// <param name="target">target </param>
public void RemoveItem(GameObject target)
{
var itemManager = target.GetComponent<vItemManager>();
RemoveItem(itemManager);
}
/// <summary>
/// Remove item of the target <seealso cref="vItemManager"/>
/// </summary>
/// <param name="target">target</param>
public void RemoveItem(vItemManager itemManager)
{
if (itemManager)
{
var item = GetItem(itemManager);
if (item != null)
{
if (type == vRemoveCurrentItem.Type.UnequipItem)
{
itemManager.UnequipItem(item);
}
else if (type == vRemoveCurrentItem.Type.DestroyItem)
{
itemManager.DestroyItem(item, 1);
}
else
{
itemManager.DropItem(item, 1);
}
}
}
}
vItem GetItem(vItemManager itemManager)
{
if (getItemByName)
{
// Check if you have an item via name (string) in your Inventory
if (itemManager.ContainItem(itemName))
{
return itemManager.GetItem(itemName);
}
}
else
{
// Check if you have an item via ID (integer) in your Inventory
if (itemManager.ContainItem(itemID))
{
return itemManager.GetItem(itemID);
}
}
return null;
}
}
}

View File

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

View File

@@ -0,0 +1,185 @@
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Invector.vItemManager
{
public static class vSaveLoadInventory
{
public static string InventoryDataFile = Application.dataPath + Path.DirectorySeparatorChar + "InventoryData.json";
/// <summary>
/// Create a Json text from Inventory EquipAreas and ItemManager Items
/// </summary>
/// <param name="itemManager">Target ItemManaget</param>
/// <returns>Json file text</returns>
public static string InventoryToJsonText(vItemManager itemManager)
{
if (!itemManager.inventory) return string.Empty;
InventoryData data = new InventoryData();
vEquipArea[] equipAreas = itemManager.inventory.equipAreas;
for (int i = 0; i < equipAreas.Length; i++)
{
EquipAreaData equipAreaData = new EquipAreaData();
equipAreaData.indexOfSelectedSlot = equipAreas[i].indexOfEquippedItem;
for (int e = 0; e < equipAreas[i].equipSlots.Count; e++)
{
SlotData equipAreaSlotData = new SlotData();
equipAreaSlotData.hasItem = equipAreas[i].equipSlots[e].item != null;
if (equipAreaSlotData.hasItem)
{
equipAreaSlotData.indexOfItem = itemManager.items.IndexOf(equipAreas[i].equipSlots[e].item);
}
equipAreaData.slotsData.Add(equipAreaSlotData);
}
data.equipAreas.Add(equipAreaData);
}
for (int i = 0; i < itemManager.items.Count; i++)
{
data.itemReferences.Add(new ItemReference(itemManager.items[i]));
}
return JsonUtility.ToJson(data, true);
}
/// <summary>
/// Load json file from <seealso cref="InventoryDataFile"/>
/// </summary>
/// <returns>Json file text</returns>
public static string LoadInventoryJasonText()
{
if (File.Exists(InventoryDataFile)) return File.ReadAllText(InventoryDataFile);
return string.Empty;
}
/// <summary>
/// Save inventory items and occupied equipSlots
/// </summary>
/// <param name="itemManager"></param>
public static void SaveInventory(this vItemManager itemManager)
{
string json = InventoryToJsonText(itemManager);
if (!string.IsNullOrEmpty(json))
{
File.WriteAllText(InventoryDataFile, json);
itemManager.onSaveItems.Invoke();
}
}
/// <summary>
/// Load inventory items and occupied equipSlots
/// </summary>
/// <param name="itemManager"></param>
public static void LoadInventory(this vItemManager itemManager)
{
string json = LoadInventoryJasonText();
if (!string.IsNullOrEmpty(json))
{
InventoryData data = new InventoryData();
JsonUtility.FromJsonOverwrite(json, data);
itemManager.items = data.GetItems(itemManager.itemListData);
vEquipArea[] equipAreas = itemManager.inventory.equipAreas;
for (int i = 0; i < equipAreas.Length; i++)
{
if (i < data.equipAreas.Count)
{
vEquipArea area = equipAreas[i];
EquipAreaData areaData = data.equipAreas[i];
area.indexOfEquippedItem = areaData.indexOfSelectedSlot;
for (int e = 0; e < equipAreas[i].equipSlots.Count; e++)
{
if (e < areaData.slotsData.Count)
{
SlotData slotData = areaData.slotsData[e];
vEquipSlot slot = equipAreas[i].equipSlots[e];
itemManager.temporarilyIgnoreItemAnimation = true;
if (slotData.hasItem)
{
area.AddItemToEquipSlot(e, itemManager.items[slotData.indexOfItem]);
}
else area.RemoveItemOfEquipSlot(e);
}
}
}
}
}
itemManager.inventory.UpdateInventory();
itemManager.temporarilyIgnoreItemAnimation = false;
itemManager.onLoadItems.Invoke();
}
[System.Serializable]
class InventoryData
{
/// <summary>
/// List of <see cref="ItemReference"/>
/// </summary>
public List<ItemReference> itemReferences = new List<ItemReference>();
/// <summary>
/// List of <seealso cref="EquipAreaData"/>
/// </summary>
public List<EquipAreaData> equipAreas = new List<EquipAreaData>();
/// <summary>
/// Get <seealso cref="vItem"/> from <seealso cref="ItemReference"/>
/// </summary>
/// <param name="itemListData"></param>
/// <returns></returns>
public List<vItem> GetItems(vItemListData itemListData)
{
List<vItem> items = new List<vItem>();
for (int i = 0; i < itemReferences.Count; i++)
{
vItem item = itemListData.items.Find(a => a.id.Equals(itemReferences[i].id));
item = GameObject.Instantiate(item);
item.amount = itemReferences[i].amount;
item.attributes = itemReferences[i].attributes;
item.name = item.name.Replace("(Clone)", string.Empty);
items.Add(item);
}
return items;
}
}
[System.Serializable]
class EquipAreaData
{
/// <summary>
/// List of <seealso cref="SlotData"/>
/// </summary>
public List<SlotData> slotsData = new List<SlotData>();
public int indexOfSelectedSlot;
}
[System.Serializable]
class SlotData
{
public bool hasItem;
public int indexOfItem;
}
[System.Serializable]
class ItemReference
{
[SerializeField] public int amount;
[SerializeField] public int id;
[SerializeField] public List<vItemAttribute> attributes;
public ItemReference(vItem item)
{
amount = item.amount;
id = item.id;
attributes = item.attributes;
}
}
}
}

View File

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

View File

@@ -0,0 +1,68 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Invector
{
public class vAutoScrollVertical : MonoBehaviour
{
private ScrollRect sr;
RectTransform contentRect;
public void Awake()
{
sr = this.gameObject.GetComponent<ScrollRect>();
if (sr)
{
contentRect = sr.content;
}
}
void Update()
{
OnUpdateSelected();
}
public void OnUpdateSelected()
{
GameObject selected = EventSystem.current.currentSelectedGameObject;
if (selected == null || selected.transform.parent != contentRect.transform) return;
// helper vars
float contentHeight = sr.content.rect.height;
float viewportHeight = sr.viewport.rect.height;
// what bounds must be visible?
float centerLine = selected.transform.localPosition.y; // selected item's center
float upperBound = centerLine + (selected.GetComponent<RectTransform>().rect.height / 2f); // selected item's upper bound
float lowerBound = centerLine - (selected.GetComponent<RectTransform>().rect.height / 2f); // selected item's lower bound
// what are the bounds of the currently visible area?
float lowerVisible = (contentHeight - viewportHeight) * sr.normalizedPosition.y - (contentHeight * 0.5f);
float upperVisible = lowerVisible + viewportHeight;
// is our item visible right now?
float desiredLowerBound;
if (upperBound > upperVisible)
{
// need to scroll up to upperBound
desiredLowerBound = upperBound - viewportHeight + selected.GetComponent<RectTransform>().rect.height;
}
else if (lowerBound < lowerVisible)
{
// need to scroll down to lowerBound
desiredLowerBound = lowerBound - selected.GetComponent<RectTransform>().rect.height;
}
else
{
// item already visible - all good
return;
}
// normalize and set the desired viewport
float normalizedDesired = (desiredLowerBound + contentHeight) / (contentHeight - viewportHeight);
var normalizedPosition = new Vector2(0f, Mathf.Clamp01(normalizedDesired));
sr.normalizedPosition = Vector2.Lerp(sr.normalizedPosition, normalizedPosition, 10 * Time.fixedDeltaTime);
}
}
}

View File

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

View File

@@ -0,0 +1,87 @@
using Invector.vCharacterController;
using System.Collections.Generic;
using UnityEngine;
namespace Invector.vItemManager
{
[vClassHeader("Control Area By Input", "Use to select an EquipArea when you press a Input")]
public class vControlAreaByInput : vMonoBehaviour
{
public List<SlotsSelector> slotsSelectors;
public vEquipArea equipArea;
public vInventory inventory;
public delegate void OnSelectSlot(int indexOfSlot);
public event OnSelectSlot onSelectSlot;
protected virtual void Start()
{
inventory = GetComponentInParent<vInventory>();
for (int i = 0; i < slotsSelectors.Count; i++)
{
onSelectSlot += slotsSelectors[i].Select;
}
onSelectSlot?.Invoke(0);
}
protected virtual void Update()
{
if (!inventory || !equipArea || inventory.lockInventoryInput) return;
for (int i = 0; i < slotsSelectors.Count; i++)
{
if (slotsSelectors[i].input.GetButtonDown() && (inventory && !inventory.IsLocked() && !inventory.isOpen && inventory.canEquip))
{
if (slotsSelectors[i].indexOfSlot < equipArea.equipSlots.Count && slotsSelectors[i].indexOfSlot >= 0)
{
equipArea.SetEquipSlot(slotsSelectors[i].indexOfSlot);
onSelectSlot?.Invoke(slotsSelectors[i].indexOfSlot);
}
}
if (slotsSelectors[i].equipDisplay != null && slotsSelectors[i].indexOfSlot < equipArea.equipSlots.Count && slotsSelectors[i].indexOfSlot >= 0)
{
if (slotsSelectors[i].equipDisplay == null) continue;
if (equipArea.equipSlots[slotsSelectors[i].indexOfSlot].item != slotsSelectors[i].equipDisplay.item)
{
slotsSelectors[i].equipDisplay.AddItem(equipArea.equipSlots[slotsSelectors[i].indexOfSlot].item);
}
else if (equipArea.equipSlots[slotsSelectors[i].indexOfSlot].item == null && slotsSelectors[i].equipDisplay.hasItem)
{
slotsSelectors[i].equipDisplay.RemoveItem();
}
}
}
}
[System.Serializable]
public class SlotsSelector
{
public GenericInput input;
[Tooltip("Index of EquipArea Slots list")]
public int indexOfSlot;
[Tooltip("Equipment display, this is optional.\nControl the display base on selected slot.")]
public vEquipmentDisplay equipDisplay;
[vReadOnly] public bool selected;
public UnityEngine.Events.UnityEvent onSelect;
public UnityEngine.Events.UnityEvent onDeselect;
public virtual void Select(int indexOfSlot)
{
if (this.indexOfSlot != indexOfSlot && selected)
{
if (equipDisplay) equipDisplay.onDeselect.Invoke();
onDeselect.Invoke();
selected = false;
}
else if (this.indexOfSlot == indexOfSlot && !selected)
{
if (equipDisplay) equipDisplay.onSelect.Invoke();
onSelect.Invoke();
selected = true;
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,357 @@
using UnityEngine;
namespace Invector
{
using vCharacterController;
using vItemManager;
[vClassHeader("Draw/Hide Melee Weapons", "This component works with vItemManager, vWeaponHolderManager and vMeleeCombatInput", useHelpBox = true)]
public class vDrawHideMeleeWeapons : vMonoBehaviour
{
[vEditorToolbar("Default")]
public bool hideWeaponsAutomatically = false;
[vHideInInspector("hideWeaponsAutomatically")]
public float hideWeaponsTimer = 5f;
[vHelpBox("Set Lock input to Inventory when Lock method is called")]
public bool lockInventoryInputOnLock;
[vReadOnly]
public bool isLocked;
public GenericInput hideAndDrawWeaponsInput = new GenericInput("H", "LB", "LB");
[vEditorToolbar("Melee")]
[Header("Draw Immediate Conditions")]
public bool meleeWeakAttack = true;
public bool meleeStrongAttack = true;
public bool meleeBlock = true;
[vEditorToolbar("Debug")]
[vReadOnly(false)]
public bool weaponsHided;
[vReadOnly(false)]
public bool previouslyWeaponsHided;
protected float currentTimer;
protected bool forceHide;
protected virtual void Start()
{
holderManager = GetComponent<vWeaponHolderManager>();
melee = GetComponent<vMeleeCombatInput>();
if (holderManager && melee)
{
melee.onUpdate -= ControlWeapons;
melee.onUpdate += ControlWeapons;
if (melee == null) Debug.LogWarning("You're missing a vMeleeCombatInput, please add one", gameObject);
}
}
protected virtual void ControlWeapons()
{
if (isLocked || melee.cc == null || melee.cc.customAction)
return;
HandleInput();
DrawWeaponsImmediateHandle();
HideWeaponsAutomatically();
}
protected virtual GameObject RightWeaponObject(bool checkIsActve = false)
{
return melee && melee.meleeManager && melee.meleeManager.rightWeapon &&
(!checkIsActve || melee.meleeManager.rightWeapon.gameObject.activeInHierarchy) ? melee.meleeManager.rightWeapon.gameObject : null;
}
protected virtual GameObject LeftWeaponObject(bool checkIsActve = false)
{
return melee && melee.meleeManager && melee.meleeManager.leftWeapon &&
(!checkIsActve || melee.meleeManager.leftWeapon.gameObject.activeInHierarchy) ? melee.meleeManager.leftWeapon.gameObject : null;
}
public virtual vMeleeCombatInput melee { get; set; }
public virtual vWeaponHolderManager holderManager { get; set; }
public virtual void ReturnToLastState(bool immediate = false)
{
if (previouslyWeaponsHided)
{
HideWeapons(immediate);
}
else DrawWeapons(immediate);
}
public virtual void LockDrawHideInput(bool value)
{
isLocked = value;
if (lockInventoryInputOnLock && holderManager.itemManager)
holderManager.itemManager.LockInventoryInput(value);
}
public virtual void HideWeapons(bool immediate = false)
{
previouslyWeaponsHided = weaponsHided;
if (CanHideRightWeapon())
{
weaponsHided = true;
HideRightWeapon(immediate);
}
else if (CanHideLeftWeapon())
{
weaponsHided = true;
HideLeftWeapon(immediate);
}
}
public virtual void ForceHideWeapons(bool immediate = false)
{
forceHide = true;
HideWeapons(immediate);
Invoke("ResetForceHide", 1);
}
protected virtual void ResetForceHide()
{
forceHide = false;
}
public virtual void DrawWeapons(bool immediate = false)
{
if (CanDrawRightWeapon())
{
previouslyWeaponsHided = weaponsHided;
weaponsHided = false;
DrawRightWeapon(immediate);
}
else if (CanDrawLeftWeapon())
{
previouslyWeaponsHided = weaponsHided;
weaponsHided = false;
DrawLeftWeapon(immediate);
}
}
protected virtual void HideWeaponsAutomatically()
{
if (hideWeaponsAutomatically)
{
if (HideTimerConditions())
{
currentTimer += Time.deltaTime;
}
else currentTimer = 0;
if (currentTimer >= hideWeaponsTimer && !IsEquipping)
{
currentTimer = 0;
HideWeapons();
}
}
else if (currentTimer > 0) currentTimer = 0;
}
protected virtual bool HideTimerConditions()
{
return CanHideWeapons() && (CanHideRightWeapon() || CanHideLeftWeapon());
}
protected virtual bool CanHideWeapons()
{
return melee && melee.meleeManager && (forceHide || (!melee.isAttacking && !melee.isBlocking && (melee.meleeManager.rightWeapon || melee.meleeManager.leftWeapon)));
}
protected virtual bool CanDrawWeapons()
{
return melee && melee.meleeManager;
}
protected virtual bool CanHideRightWeapon()
{
return ((CanHideWeapons()) && RightWeaponObject() && RightWeaponObject().activeInHierarchy);
}
protected virtual bool CanHideLeftWeapon()
{
return (CanHideWeapons() && LeftWeaponObject() && LeftWeaponObject().activeInHierarchy);
}
protected virtual bool CanDrawRightWeapon()
{
return (CanDrawWeapons() && RightWeaponObject() && !RightWeaponObject().activeInHierarchy);
}
protected virtual bool CanDrawLeftWeapon()
{
return (CanDrawWeapons() && LeftWeaponObject() && !LeftWeaponObject().activeInHierarchy);
}
protected virtual bool IsEquipping
{
get
{
return melee != null && melee.cc && melee.cc.IsAnimatorTag("IsEquipping");
}
}
protected virtual void HandleInput()
{
if (hideAndDrawWeaponsInput.GetButtonDown() && !IsEquipping)
{
if (CanHideRightWeapon() || CanHideLeftWeapon())
{
HideWeapons();
}
else if (CanDrawRightWeapon() || CanDrawLeftWeapon())
{
DrawWeapons();
}
}
}
protected virtual void DrawWeaponsImmediateHandle()
{
if (DrawWeaponsImmediateConditions())
{
DrawWeapons(true);
}
}
protected virtual bool DrawWeaponsImmediateConditions()
{
if (!melee || melee.cc.customAction || !melee.meleeManager || (melee.meleeManager.CurrentAttackWeapon == null && melee.meleeManager.CurrentDefenseWeapon == null))
return false;
else
{
return melee.weakAttackInput.GetButton() && meleeWeakAttack || melee.strongAttackInput.GetButton() && meleeStrongAttack || melee.blockInput.GetButton() && meleeBlock;
}
}
protected virtual void HideRightWeapon(bool immediate = false)
{
var weapon = RightWeaponObject(true);
if (weapon)
{
var equipment = weapon.GetComponent<vEquipment>();
if (equipment == null || equipment.equipPoint == null || equipment.equipPoint.area == null)
{
return;
}
var holder = holderManager.GetHolder(weapon.gameObject, equipment.referenceItem.id);
HideWeaponsHandle(melee, equipment,
null,
() =>
{
if (holder) holder.SetActiveWeapon(true);
if (weapon) weapon.gameObject.SetActive(false);
if (CanHideLeftWeapon()) HideLeftWeapon(immediate);
}, immediate);
}
}
protected virtual void HideLeftWeapon(bool immediate = false)
{
var weapon = LeftWeaponObject(true);
if (weapon)
{
var equipment = weapon.GetComponent<vEquipment>();
if (equipment == null || equipment.equipPoint == null || equipment.equipPoint.area == null)
{
return;
}
var holder = holderManager.GetHolder(weapon.gameObject, equipment.referenceItem.id);
HideWeaponsHandle(melee, equipment,
null,
() =>
{
if (holder) holder.SetActiveWeapon(true);
if (weapon) weapon.gameObject.SetActive(false);
}, immediate);
}
}
protected virtual void DrawRightWeapon(bool immediate = false)
{
var weapon = RightWeaponObject();
if (weapon)
{
var equipment = weapon.GetComponent<vEquipment>();
if (equipment == null || equipment.equipPoint == null || equipment.equipPoint.area == null)
{
return;
}
if (equipment.equipPoint.area.isLockedToEquip) return;
var holder = holderManager.GetHolder(weapon.gameObject, equipment.referenceItem.id);
DrawWeaponsHandle(melee, equipment, null,
() =>
{
if (holder) holder.SetActiveWeapon(false);
if (weapon && weapon.gameObject)
weapon.gameObject.SetActive(true);
if (CanDrawLeftWeapon())
DrawLeftWeapon(immediate);
}, immediate);
}
}
protected virtual void DrawLeftWeapon(bool immediate = false)
{
var weapon = LeftWeaponObject();
if (weapon)
{
var equipment = weapon.GetComponent<vEquipment>();
if (equipment == null || equipment.equipPoint == null || equipment.equipPoint.area == null)
{
return;
}
if (equipment.equipPoint.area.isLockedToEquip) return;
var holder = holderManager.GetHolder(weapon.gameObject, equipment.referenceItem.id);
DrawWeaponsHandle(melee, equipment, null,
() =>
{
if (holder) holder.SetActiveWeapon(false);
if (weapon && weapon.gameObject)
weapon.gameObject.SetActive(true);
}, immediate);
}
}
protected virtual void DrawWeaponsHandle(vThirdPersonInput tpInput, vEquipment equipment, UnityEngine.Events.UnityAction onStart, UnityEngine.Events.UnityAction onFinish, bool immediate = false)
{
if (holderManager.inEquip && !immediate) return;
if (!immediate)
{
if (!string.IsNullOrEmpty(equipment.referenceItem.EnableAnim) && equipment != null && equipment.equipPoint != null)
{
tpInput.animator.SetBool("FlipEquip", equipment.equipPoint.equipPointName.Contains("Left"));
tpInput.animator.CrossFade(equipment.referenceItem.EnableAnim, 0.25f);
}
else immediate = true;
}
if (equipment) equipment.IsEquipped = true;
StartCoroutine(holderManager.EquipRoutine(equipment.referenceItem.enableDelayTime, immediate, onStart, onFinish));
}
protected virtual void HideWeaponsHandle(vThirdPersonInput tpInput, vEquipment equipment, UnityEngine.Events.UnityAction onStart, UnityEngine.Events.UnityAction onFinish, bool immediate = false)
{
if (holderManager.inUnequip && !immediate) return;
if (!immediate)
{
if (!string.IsNullOrEmpty(equipment.referenceItem.DisableAnim) && equipment != null && equipment.equipPoint != null)
{
tpInput.animator.SetBool("FlipEquip", equipment.equipPoint.equipPointName.Contains("Left"));
tpInput.animator.CrossFade(equipment.referenceItem.DisableAnim, 0.25f);
}
else immediate = true;
}
if (equipment) equipment.IsEquipped = false;
StartCoroutine(holderManager.UnequipRoutine(equipment.referenceItem.disableDelayTime, immediate, onStart, onFinish));
}
}
}

View File

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

View File

@@ -0,0 +1,554 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Invector.vItemManager
{
[vClassHeader("Equip Area", openClose = false)]
public class vEquipArea : vMonoBehaviour
{
public delegate void OnPickUpItem(vEquipArea area, vItemSlot slot);
public OnPickUpItem onPickUpItemCallBack;
public vInventory inventory;
public vItemWindow itemPicker;
[Tooltip("Set current equipped slot when submit an slot of this area")]
public bool setEquipSlotWhenSubmit;
[Tooltip("Skip empty slots when switching between slots")]
public bool skipEmptySlots;
public List<vEquipSlot> equipSlots;
public string equipPointName;
public Text displayNameText;
public Text displayTypeText;
public Text displayAmountText;
public Text displayDescriptionText;
public Text displayAttributesText;
[vHelpBox("You can ignore display Attributes using this property")]
public List<vItemAttributes> ignoreAttributes;
public UnityEngine.Events.UnityEvent onInitPickUpItem, onFinishPickUpItem;
public InputField.OnChangeEvent onChangeName;
public InputField.OnChangeEvent onChangeType;
public InputField.OnChangeEvent onChangeAmount;
public InputField.OnChangeEvent onChangeDescription;
public InputField.OnChangeEvent onChangeAttributes;
public OnChangeEquipmentEvent onEquipItem;
public OnChangeEquipmentEvent onUnequipItem;
public OnChangeEquipmentEvent onChangeEquipSlot;
public OnSelectEquipArea onSelectEquipArea;
public UnityEngine.UI.Toggle.ToggleEvent onSetLockToEquip;
[HideInInspector]
public virtual vEquipSlot currentSelectedSlot { get; protected set; }
public virtual vEquipSlot lastSelectedSlot { get; protected set; }
[HideInInspector]
public virtual int indexOfEquippedItem
{
get => _indexOfEquippedSlot;
set
{
if (_indexOfEquippedSlot != value || equipSlotUpdated == false)
{
equipSlotUpdated = true;
_indexOfEquippedSlot = value;
onChangeEquipSlot.Invoke(this, currentEquippedItem);
}
}
}
protected bool equipSlotUpdated;
protected int _indexOfEquippedSlot;
public virtual vItem lastEquippedItem { get; protected set; }
protected bool _isLockedToEquip { get; set; }
public bool isLockedToEquip
{
get
{
return _isLockedToEquip;
}
set
{
if (_isLockedToEquip != value) onSetLockToEquip.Invoke(value);
_isLockedToEquip = value;
}
}
public bool ignoreEquipEvents { get; set; }
/// <summary>
/// used to ignore <see cref="onEquipItem"/> event. if true, the inventory will just add the equipment to area but dont will send to Equip the item. you will nedd to call <see cref="EquipCurrentSlot"/> to equip the item in the area.
/// </summary>
internal bool isInit { get; set; }
public virtual void Init()
{
if (!isInit) Start();
}
protected virtual void Start()
{
if (!isInit)
{
isInit = true;
inventory = GetComponentInParent<vInventory>();
if (equipSlots.Count == 0)
{
var equipSlotsArray = GetComponentsInChildren<vEquipSlot>(true);
equipSlots = equipSlotsArray.vToList();
}
foreach (vEquipSlot slot in equipSlots)
{
slot.onSubmitSlotCallBack = OnSubmitSlot;
slot.onSelectSlotCallBack = OnSelectSlot;
slot.onDeselectSlotCallBack = OnDeselect;
onSetLockToEquip.AddListener(slot.SetLockToEquip);
if (slot.displayAmountText) slot.displayAmountText.text = "";
slot.onChangeAmount.Invoke("");
}
}
}
/// <summary>
/// Current Equipped Slot
/// </summary>
public virtual vEquipSlot currentEquippedSlot
{
get
{
return equipSlots[indexOfEquippedItem];
}
}
/// <summary>
/// Item in Current Equipped Slot
/// </summary>
public virtual vItem currentEquippedItem
{
get
{
return currentEquippedSlot.item;
}
}
/// <summary>
/// All valid slot <seealso cref="vItemSlot.isValid"/>
/// </summary>
public virtual List<vEquipSlot> ValidSlots
{
get { return equipSlots.FindAll(slot => slot.isValid && (!skipEmptySlots || slot.item != null)); }
}
/// <summary>
/// Check if Item is in Area
/// </summary>
/// <param name="item">item to check</param>
/// <returns></returns>
public virtual bool ContainsItem(vItem item)
{
return equipSlots.Find(slot => slot.item == item) != null;
}
/// <summary>
/// Event called from Inventory slot UI on Submit
/// </summary>
/// <param name="slot"></param>
public virtual void OnSubmitSlot(vItemSlot slot)
{
lastSelectedSlot = currentSelectedSlot;
if (itemPicker != null)
{
currentSelectedSlot = slot as vEquipSlot;
if (setEquipSlotWhenSubmit)
{
SetEquipSlot(equipSlots.IndexOf(currentSelectedSlot));
}
itemPicker.gameObject.SetActive(true);
itemPicker.onCancelSlot.RemoveAllListeners();
itemPicker.onCancelSlot.AddListener(CancelCurrentSlot);
itemPicker.CreateEquipmentWindow(inventory.items, currentSelectedSlot.itemType, slot.item, OnPickItem);
onInitPickUpItem.Invoke();
}
}
/// <summary>
/// Event called to cancel Submit action
/// </summary>
public virtual void CancelCurrentSlot()
{
if (currentSelectedSlot == null)
currentSelectedSlot = lastSelectedSlot;
if (currentSelectedSlot != null)
currentSelectedSlot.OnCancel();
onFinishPickUpItem.Invoke();
}
/// <summary>
/// Unequip Item of the Slot
/// </summary>
/// <param name="slot">target slot</param>
public virtual void UnequipItem(vEquipSlot slot)
{
if (slot)
{
vItem item = slot.item;
if (equipSlots[indexOfEquippedItem].item == item)
lastEquippedItem = item;
slot.RemoveItem();
onUnequipItem.Invoke(this, item);
}
}
/// <summary>
/// Unequip Item if is present in slots
/// </summary>
/// <param name="item"></param>
public virtual void UnequipItem(vItem item)
{
var slot = equipSlots.Find(_slot => _slot.item == item);
if (slot)
{
if (equipSlots[indexOfEquippedItem].item == item) lastEquippedItem = item;
slot.RemoveItem();
onUnequipItem.Invoke(this, item);
}
}
/// <summary>
/// Unequip <seealso cref="currentEquippedItem"/>
/// </summary>
public virtual void UnequipCurrentItem()
{
if (currentSelectedSlot && currentSelectedSlot.item)
{
var _item = currentSelectedSlot.item;
if (equipSlots[indexOfEquippedItem].item == _item) lastEquippedItem = _item;
currentSelectedSlot.RemoveItem();
onUnequipItem.Invoke(this, _item);
}
}
/// <summary>
/// Event called from inventory UI when select an slot
/// </summary>
/// <param name="slot">target slot</param>
public virtual void OnSelectSlot(vItemSlot slot)
{
if (equipSlots.Contains(slot as vEquipSlot))
currentSelectedSlot = slot as vEquipSlot;
else currentSelectedSlot = null;
onSelectEquipArea.Invoke(this);
CreateFullItemDescription(slot);
}
/// <summary>
/// Event called from inventory UI when unselect an slot
/// </summary>
/// <param name="slot">target slot</param>
public virtual void OnDeselect(vItemSlot slot)
{
if (equipSlots.Contains(slot as vEquipSlot))
{
currentSelectedSlot = null;
}
}
/// <summary>
/// Create item description
/// </summary>
/// <param name="slot">target slot</param>
protected virtual void CreateFullItemDescription(vItemSlot slot)
{
var _name = slot.item ? slot.item.name : "";
var _type = slot.item ? slot.item.ItemTypeText() : "";
var _amount = slot.item ? slot.item.amount.ToString() : "";
var _description = slot.item ? slot.item.description : "";
var _attributes = slot.item ? slot.item.GetItemAttributesText(ignoreAttributes) : "";
if (displayNameText) displayNameText.text = _name;
onChangeName.Invoke(_name);
if (displayTypeText) displayTypeText.text = _type;
onChangeType.Invoke(_type);
if (displayAmountText) displayAmountText.text = _amount;
onChangeAmount.Invoke(_amount);
if (displayDescriptionText) displayDescriptionText.text = _description;
onChangeDescription.Invoke(_description);
if (displayAttributesText) displayAttributesText.text = _attributes;
onChangeAttributes.Invoke(_attributes);
}
/// <summary>
/// Event called from inventory UI to open <see cref="vItemWindow"/> when submit slot
/// </summary>
/// <param name="slot">target slot</param>
public virtual void OnPickItem(vItemSlot slot)
{
if (!currentSelectedSlot)
currentSelectedSlot = lastSelectedSlot;
if (!currentSelectedSlot)
return;
if (currentSelectedSlot.item != null && slot.item != currentSelectedSlot.item)
{
currentSelectedSlot.item.isInEquipArea = false;
var item = currentSelectedSlot.item;
if (item == slot.item) lastEquippedItem = item;
currentSelectedSlot.RemoveItem();
onUnequipItem.Invoke(this, item);
}
if (slot.item != currentSelectedSlot.item)
{
if (onPickUpItemCallBack != null)
onPickUpItemCallBack(this, slot);
currentSelectedSlot.AddItem(slot.item);
if (!ignoreEquipEvents) onEquipItem.Invoke(this, currentSelectedSlot.item);
}
currentSelectedSlot.OnCancel();
currentSelectedSlot = null;
lastSelectedSlot = null;
itemPicker.gameObject.SetActive(false);
onFinishPickUpItem.Invoke();
}
/// <summary>
/// Equip next slot <seealso cref="currentEquippedItem"/>
/// </summary>
public virtual void NextEquipSlot()
{
if (equipSlots == null || equipSlots.Count == 0) return;
lastEquippedItem = currentEquippedItem;
var validEquipSlots = equipSlots;
var index = indexOfEquippedItem;
for (int i = 0; i < equipSlots.Count; i++)
{
if (index + 1 < equipSlots.Count)
{
index++;
}
else index = 0;
if (equipSlots[index].isValid && (!skipEmptySlots || equipSlots[index].item != null))
{
indexOfEquippedItem = index;
break;
}
}
if (lastEquippedItem != currentEquippedItem)
{
if (currentEquippedItem != null && !ignoreEquipEvents)
onEquipItem.Invoke(this, currentEquippedItem);
onUnequipItem.Invoke(this, lastEquippedItem);
}
}
/// <summary>
/// Equip previous slot <seealso cref="currentEquippedItem"/>
/// </summary>
public virtual void PreviousEquipSlot()
{
if (equipSlots == null || equipSlots.Count == 0) return;
lastEquippedItem = currentEquippedItem;
var validEquipSlots = equipSlots;
var index = indexOfEquippedItem;
for (int i = 0; i < equipSlots.Count; i++)
{
if (index - 1 >= 0)
{
index--;
}
else index = equipSlots.Count - 1;
if (equipSlots[index].isValid && (!skipEmptySlots || equipSlots[index].item != null))
{
indexOfEquippedItem = index;
break;
}
}
if (lastEquippedItem != currentEquippedItem)
{
if (currentEquippedItem != null && !ignoreEquipEvents)
onEquipItem.Invoke(this, currentEquippedItem);
onUnequipItem.Invoke(this, lastEquippedItem);
}
}
/// <summary>
/// Equip slot <see cref="currentEquippedItem"/>
/// </summary>
/// <param name="indexOfSlot">index of target slot</param>
public virtual void SetEquipSlot(int indexOfSlot)
{
if (equipSlots == null || equipSlots.Count == 0) return;
if (indexOfSlot < equipSlots.Count && indexOfSlot >= 0 && equipSlots[indexOfSlot].isValid)
{
if (skipEmptySlots == false || equipSlots[indexOfSlot].item != null)
{
lastEquippedItem = currentEquippedItem;
indexOfEquippedItem = indexOfSlot;
if (currentEquippedItem != null && !ignoreEquipEvents)
{
onEquipItem.Invoke(this, currentEquippedItem);
}
if (currentEquippedItem != lastEquippedItem)
onUnequipItem.Invoke(this, lastEquippedItem);
}
}
}
/// <summary>
/// Equip current slot
/// </summary>
public virtual void EquipCurrentSlot()
{
if (!currentEquippedSlot || (currentEquippedSlot.item != null && currentEquippedSlot.item.isEquiped)) return;
if (currentEquippedItem) onEquipItem.Invoke(this, currentEquippedItem);
else if (lastEquippedItem) onUnequipItem.Invoke(this, lastEquippedItem);
}
/// <summary>
/// Add an item to an slot
/// </summary>
/// <param name="slot">target Slot</param>
/// <param name="item">target Item</param>
public virtual void AddItemToEquipSlot(vItemSlot slot, vItem item, bool autoEquip = false)
{
if (slot is vEquipSlot && equipSlots.Contains(slot as vEquipSlot))
{
AddItemToEquipSlot(equipSlots.IndexOf(slot as vEquipSlot), item, autoEquip);
}
}
/// <summary>
/// Add an item to an slot
/// </summary>
/// <param name="indexOfSlot">index of target Slot</param>
/// <param name="item">target Item</param>
public virtual void AddItemToEquipSlot(int indexOfSlot, vItem item, bool autoEquip = false)
{
if (indexOfSlot < equipSlots.Count && item != null)
{
var slot = equipSlots[indexOfSlot];
if (slot != null && slot.isValid && slot.itemType.Contains(item.type))
{
var sameSlot = equipSlots.Find(s => s.item == item && s != slot);
if (sameSlot != null)
RemoveItemOfEquipSlot(equipSlots.IndexOf(sameSlot));
if (slot.item != null && slot.item != item)
{
var lastSlotItem = slot.item;
if (currentEquippedItem == lastSlotItem) lastEquippedItem = lastSlotItem;
slot.RemoveItem();
lastSlotItem.isInEquipArea = false;
onUnequipItem.Invoke(this, lastSlotItem);
}
item.isInEquipArea = true;
slot.AddItem(item);
if (autoEquip)
SetEquipSlot(indexOfSlot);
else if (!ignoreEquipEvents)
onEquipItem.Invoke(this, item);
}
}
}
/// <summary>
/// Remove item of an slot
/// </summary>
/// <param name="slot">target Slot</param>
public virtual void RemoveItemOfEquipSlot(vItemSlot slot)
{
if (slot is vEquipSlot && equipSlots.Contains(slot as vEquipSlot))
{
RemoveItemOfEquipSlot(equipSlots.IndexOf(slot as vEquipSlot));
}
}
/// <summary>
/// Remove item of an slot
/// </summary>
/// <param name="slot">index of target Slot</param>
public void RemoveItemOfEquipSlot(int indexOfSlot)
{
if (indexOfSlot < equipSlots.Count)
{
var slot = equipSlots[indexOfSlot];
if (slot != null && slot.item != null)
{
var item = slot.item;
item.isInEquipArea = false;
if (currentEquippedItem == item) lastEquippedItem = currentEquippedItem;
slot.RemoveItem();
onUnequipItem.Invoke(this, item);
}
}
}
/// <summary>
/// Add item to current equiped slot
/// </summary>
/// <param name="item">target item</param>
public virtual void AddCurrentItem(vItem item)
{
if (indexOfEquippedItem < equipSlots.Count)
{
var slot = equipSlots[indexOfEquippedItem];
if (slot.item != null && item != slot.item)
{
if (currentEquippedItem == slot.item) lastEquippedItem = slot.item;
slot.item.isInEquipArea = false;
var lastSlot = equipSlots.Find(i => i.item == item);
if (lastSlot != null)
{
lastSlot.RemoveItem();
}
slot.RemoveItem();
onUnequipItem.Invoke(this, lastEquippedItem);
}
else
{
var lastSlot = equipSlots.Find(i => i.item == item);
if (lastSlot != null)
lastSlot.RemoveItem();
}
slot.AddItem(item);
if (!ignoreEquipEvents) onEquipItem.Invoke(this, item);
}
}
/// <summary>
/// Remove current equiped Item
/// </summary>
public virtual void RemoveCurrentItem()
{
if (!currentEquippedItem) return;
lastEquippedItem = currentEquippedItem;
equipSlots[indexOfEquippedItem].RemoveItem();
onUnequipItem.Invoke(this, lastEquippedItem);
}
}
}

View File

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

View File

@@ -0,0 +1,67 @@
using UnityEngine;
using System.Collections.Generic;
namespace Invector.vItemManager
{
public class vEquipAreaControl : MonoBehaviour
{
[HideInInspector]
public List<vEquipArea> equipAreas;
protected virtual void Start()
{
equipAreas = GetComponentsInChildren<vEquipArea>().vToList();
foreach (vEquipArea area in equipAreas)
area.onPickUpItemCallBack = OnPickUpItemCallBack;
vInventory inventory = GetComponentInParent<vInventory>();
if (inventory)
inventory.onOpenCloseInventory.AddListener(OnOpen);
}
/// <summary>
/// Event called when inventory open or close
/// </summary>
/// <param name="value">is open</param>
public virtual void OnOpen(bool value)
{
}
/// <summary>
/// Event called when an area pick up an item
/// </summary>
/// <param name="area">target area</param>
/// <param name="slot">target slot</param>
public virtual void OnPickUpItemCallBack(vEquipArea area, vItemSlot slot)
{
for (int i = 0; i < equipAreas.Count; i++)
{
var sameSlots = equipAreas[i].equipSlots.FindAll(slotInArea => slotInArea != slot && slotInArea.item != null && slotInArea.item == slot.item);
for (int a = 0; a < sameSlots.Count; a++)
{
equipAreas[i].UnequipItem(sameSlots[a]);
}
}
CheckTwoHandItem(area, slot);
}
protected virtual void CheckTwoHandItem(vEquipArea area, vItemSlot slot)
{
if (slot.item == null) return;
var opposite = equipAreas.Find(_area => _area != null && area.equipPointName.Equals("LeftArm") && _area.currentEquippedItem != null);
//var RightEquipmentController = changeEquipmentControllers.Find(equipCtrl => equipCtrl.equipArea != null && equipCtrl.equipArea.equipPointName.Equals("RightArm"));
if (area.equipPointName.Equals("LeftArm"))
opposite = equipAreas.Find(_area => _area != null && area.equipPointName.Equals("RightArm") && _area.currentEquippedItem != null);
else if (!area.equipPointName.Equals("RightArm"))
{
return;
}
if (opposite != null && (slot.item.twoHandWeapon || opposite.currentEquippedItem.twoHandWeapon))
{
opposite.onUnequipItem.Invoke(opposite, slot.item);
opposite.UnequipItem(slot as vEquipSlot);
}
}
}
}

View File

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

View File

@@ -0,0 +1,92 @@
using Invector.vCharacterController;
using UnityEngine;
namespace Invector.vItemManager
{
public class vEquipItemToArea : MonoBehaviour
{
public vItemWindowDisplay itemWindow;
public AreaToEquip[] areasToEquip;
public GenericInput cancelInput = new GenericInput("Escape", "B", "B");
public UnityEngine.Events.UnityEvent onEquip;
public UnityEngine.Events.UnityEvent onCancel;
[System.Serializable]
public class AreaToEquip
{
[Tooltip("Target EquipArea to Equip")]
public vEquipArea area;
[Tooltip("Target EquipSlot of the EquipArea to Equip")]
public int slotIndex;
[Tooltip("Optional button to equip on press")]
public UnityEngine.UI.Button optionalButton;
[Tooltip("Input to equip on press")]
public GenericInput input = new GenericInput("Alpha 1", "B", "B");
internal void CheckInput(vItem item,UnityEngine.Events.UnityEvent onEquip)
{
if(input.GetButtonDown())
{
Equip(item);
onEquip?.Invoke();
}
}
internal void Equip(vItem item)
{
if (area) area.AddItemToEquipSlot(slotIndex, item);
}
}
protected UnityEngine.Events.UnityAction onEquipAction;
private void Start()
{
onEquipAction = () => { onEquip.Invoke(); };
for(int i=0;i<areasToEquip.Length;i++)
{
if(areasToEquip[i].optionalButton)
{
AreaToEquip areaToEquip = areasToEquip[i];
areasToEquip[i].optionalButton.onClick.AddListener(() =>
{
Equip(areaToEquip);
});
}
}
}
protected virtual void Update()
{
if(itemWindow && itemWindow.currentSelectedSlot && itemWindow.currentSelectedSlot.item)
{
for (int i = 0; i < areasToEquip.Length; i++)
{
areasToEquip[i].CheckInput(itemWindow.currentSelectedSlot.item, onEquip);
}
}
if(cancelInput.GetButtonDown())
{
onCancel.Invoke();
}
}
protected virtual void Equip(AreaToEquip areaToEquip)
{
if (itemWindow && itemWindow.currentSelectedSlot && itemWindow.currentSelectedSlot.item)
{
areaToEquip.Equip(itemWindow.currentSelectedSlot.item);
onEquip.Invoke();
}
}
public virtual void Equip(int index)
{
if (index < areasToEquip.Length)
{
AreaToEquip areaToEquip = areasToEquip[index];
Equip(areaToEquip);
}
}
}
}

View File

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

View File

@@ -0,0 +1,13 @@
using UnityEngine;
namespace Invector.vItemManager
{
[System.Serializable]
public class vEquipProperties
{
public vItem targetItem;
public GameObject sender;
public Transform targetEquipPoint;
}
}

View File

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

View File

@@ -0,0 +1,81 @@
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace Invector.vItemManager
{
public class vEquipSlot : vItemSlot
{
[vEditorToolbar("Default")]
[vHelpBox("Select what ItemType this EquipSlot will equip", vHelpBoxAttribute.MessageType.Warning)]
public List<vItemType> itemType;
public bool clickToOpen = true;
public bool autoDeselect = true;
public UnityEvent onCancel, onSetLockToEquip, onUnlockToEquip;
public virtual void SetLockToEquip(bool value)
{
if (value) onSetLockToEquip.Invoke();
else onUnlockToEquip.Invoke();
}
/// <summary>
/// Add item to slot
/// </summary>
/// <param name="item">target item</param>
public override void AddItem(vItem item)
{
if (item) item.isInEquipArea = true;
base.AddItem(item);
}
/// <summary>
/// Enable or disable checkIcon
/// </summary>
/// <param name="value">Enable or disable value</param>
public override void CheckItem(bool value)
{
if (checkIcon && checkIcon.gameObject.activeSelf)
{
checkIcon.gameObject.SetActive(false);
}
}
/// <summary>
/// Remove current item of the slot
/// </summary>
public override void RemoveItem()
{
if (item != null) item.isInEquipArea = false;
base.RemoveItem();
}
/// <summary>
/// Event called when EquipSlot actions is canceled
/// </summary>
public virtual void OnCancel()
{
onCancel.Invoke();
}
#region UnityEngine.EventSystems Implementation
public override void OnDeselect(BaseEventData eventData)
{
if (autoDeselect)
base.OnDeselect(eventData);
}
public override void OnPointerExit(PointerEventData eventData)
{
if (autoDeselect)
base.OnPointerExit(eventData);
}
public override void OnPointerClick(PointerEventData eventData)
{
if (clickToOpen)
base.OnPointerClick(eventData);
}
#endregion
}
}

View File

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

View File

@@ -0,0 +1,58 @@
using UnityEngine;
namespace Invector.vItemManager
{
/// <summary>
/// Equipments of the Inventory that needs to be instantiated
/// </summary>
[vClassHeader("Equipment", openClose = false, helpBoxText = "Use this component if you also use the ItemManager in your Character")]
public partial class vEquipment : vMonoBehaviour
{
public OnHandleItemEvent onEquip, onUnequip;
[SerializeField, vReadOnly] protected vItem item;
[SerializeField, vReadOnly] protected bool isEquipped;
public EquipPoint equipPoint { get; set; }
/// <summary>
/// Equipment is equipped
/// </summary>
public virtual bool IsEquipped { get => isEquipped; set => isEquipped = value; }
/// <summary>
/// Event called when equipment is destroyed
/// </summary>
public virtual void OnDestroy()
{
}
/// <summary>
/// Item representing the equipment
/// </summary>
public virtual vItem referenceItem
{
get => item;
protected set => item = value;
}
/// <summary>
/// Event called when the item is equipped
/// </summary>
/// <param name="item">target item</param>
public virtual void OnEquip(vItem item)
{
IsEquipped = true;
referenceItem = item;
onEquip.Invoke(item);
}
/// <summary>
/// Event called when the item is unquipped
/// </summary>
/// <param name="item">target item</param>
public virtual void OnUnequip(vItem item)
{
IsEquipped = false;
onUnequip.Invoke(item);
}
}
}

View File

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

View File

@@ -0,0 +1,43 @@
using UnityEngine.UI;
namespace Invector.vItemManager
{
public class vEquipmentDisplay : vItemSlot
{
public Text slotIdentifier;
public InputField.OnChangeEvent onChangeIdentifier;
public UnityEngine.Events.UnityEvent onSelect, onDeselect;
public bool hasItem;
public UnityEngine.Events.UnityEvent onSetLockToEquip, onUnlockToEquip;
public virtual void SetLockToEquip(bool value)
{
if (value) onSetLockToEquip.Invoke();
else onUnlockToEquip.Invoke();
}
public virtual void ItemIdentifier(int identifier = 0, bool showIdentifier = false)
{
if (!slotIdentifier) return;
if (showIdentifier)
{
if (slotIdentifier)
slotIdentifier.text = identifier.ToString();
onChangeIdentifier.Invoke(identifier.ToString());
}
else
{
if (slotIdentifier)
slotIdentifier.text = string.Empty;
onChangeIdentifier.Invoke(string.Empty);
}
}
public override void AddItem(vItem item)
{
base.AddItem(item);
hasItem = item != null;
}
}
}

View File

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

View File

@@ -0,0 +1,52 @@
using System.Collections.Generic;
using UnityEngine;
namespace Invector.vItemManager
{
public class vEquipmentReferenceControl : MonoBehaviour
{
[System.Serializable]
public class vEquipmentReference
{
public string name;
public int id;
public vEquipment equipment;
}
public List<vEquipmentReference> equipmentReferences;
protected virtual void Awake()
{
vItemManager itemManager = GetComponentInParent<vItemManager>();
itemManager.onEquipItem.AddListener(OnEquip);
itemManager.onUnequipItem.AddListener(OnUniquip);
}
protected virtual void OnEquip(vEquipArea equipArea, vItem equipment)
{
if(equipment) SetActiveEquipment(equipment, true);
}
protected virtual void OnUniquip(vEquipArea equipArea, vItem equipment)
{
if (equipment) SetActiveEquipment(equipment, false);
}
public virtual void SetActiveEquipment( vItem item,bool active)
{
var equipments = equipmentReferences.FindAll(e => e.id.Equals(item.id));
for (int i = 0; i < equipments.Count; i++)
{
if (equipments[i].equipment)
{
equipments[i].equipment.gameObject.SetActive(active);
if(active)
{
equipments[i].equipment.OnEquip(item);
}
else equipments[i].equipment.OnUnequip(item);
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,46 @@
using UnityEngine;
using UnityEngine.UI;
namespace Invector
{
public class vGridLayoutExpand : MonoBehaviour
{
GridLayoutGroup grid;
public int count;
RectTransform rect;
float multiple;
float oldMultiple;
void Start()
{
grid = GetComponent<GridLayoutGroup>();
rect = GetComponent<RectTransform>();
}
void OnDrawGizmos()
{
if (Application.isPlaying) return;
grid = GetComponent<GridLayoutGroup>();
rect = GetComponent<RectTransform>();
UpdateBottomSize();
}
void UpdateBottomSize()
{
double value = ((double)rect.childCount / (double)count);
multiple = (float)System.Math.Round(value, System.MidpointRounding.AwayFromZero) + 1;
if (multiple != oldMultiple)
{
var scale = rect.offsetMin;
var desiredScaleY = (grid.cellSize.y + grid.spacing.y) * -multiple;
scale.y = desiredScaleY;
rect.offsetMin = scale;
oldMultiple = multiple;
}
}
void Update()
{
UpdateBottomSize();
}
}
}

View File

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

View File

@@ -0,0 +1,15 @@
using UnityEngine;
using System.Collections.Generic;
namespace Invector
{
[System.Serializable]
public class vHandler
{
public Transform defaultHandler;
public List<Transform> customHandlers;
public vHandler()
{
customHandlers = new List<Transform>();
}
}
}

View File

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

View File

@@ -0,0 +1,16 @@
using UnityEngine;
namespace Invector.vItemManager
{
[System.Obsolete("Class is no longer used and will be removed in the future")]
public interface vIEquipment
{
Transform transform { get; }
GameObject gameObject { get; }
bool isEquiped { get; }
EquipPoint equipPoint{ get; set; }
vItem referenceItem { get; }
void OnEquip(vItem item);
void OnUnequip(vItem item);
}
}

View File

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

View File

@@ -0,0 +1,513 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Invector.vItemManager
{
using vCharacterController;
[vClassHeader("Inventory")]
public class vInventory : vMonoBehaviour
{
#region Item Variables
// delegates to help handle items
public delegate List<vItem> GetItemsDelegate();
public delegate void AddItemDelegate(ItemReference itemReference, bool immediate = true, UnityEngine.Events.UnityAction<vItem> onFinish = null);
public delegate bool LockInventoryInputEvent();
public delegate int GetAllAmountDelegate(int id);
public delegate void OnUpdateInventoryDelegate();
/// <summary>
/// Action to get the current items from your Inventory
/// </summary>
public GetItemsDelegate GetItemsHandler;
/// <summary>
/// Action to get all items from your <seealso cref="vItemListData"/>
/// </summary>
public GetItemsDelegate GetItemsAllHandler;
/// <summary>
/// Action to add items to a Inventory
/// </summary>
public AddItemDelegate AddItemsHandler;
/// <summary>
/// Action to get the same items quantity
/// </summary>
public GetAllAmountDelegate GetAllAmount;
/// <summary>
/// Action to lock the inventory input
/// </summary>
public LockInventoryInputEvent IsLockedEvent;
/// <summary>
/// Action to Update the Inventory methods
/// </summary>
public event OnUpdateInventoryDelegate OnUpdateInventory;
[vEditorToolbar("Settings")]
[vHelpBox("True: Play Item animation when the timeScale is 0 \n False: Ignore Item animation if timeScale equals 0")]
public bool playItemAnimation = true;
[Range(0, 1)]
public float timeScaleWhileIsOpen = 0;
[Tooltip("Check true to not destroy this object when changing scenes")]
public bool dontDestroyOnLoad = true;
public List<ChangeEquipmentControl> changeEquipmentControllers;
[vEditorToolbar("Input Mapping")]
public GenericInput openInventory = new GenericInput("I", "Start", "Start");
public GenericInput removeEquipment = new GenericInput("Mouse1", "X", "X");
[Header("This fields will override the EventSystem Input")]
public GenericInput horizontal = new GenericInput("Horizontal", "D-Pad Horizontal", "Horizontal");
public GenericInput vertical = new GenericInput("Vertical", "D-Pad Vertical", "Vertical");
public GenericInput submit = new GenericInput("Return", "A", "A");
public GenericInput cancel = new GenericInput("Backspace", "B", "B");
[vEditorToolbar("Events")]
public OnOpenCloseInventory onOpenCloseInventory;
public OnHandleItemEvent onUseItem;
public OnChangeItemAmount onDestroyItem, onDropItem;
public OnChangeEquipmentEvent onEquipItem, onUnequipItem;
[SerializeField] protected UnityEngine.Events.UnityEvent onUpdateInventory;
[HideInInspector]
public bool isOpen, canEquip, lockInventoryInput;
//[HideInInspector]
public vEquipArea[] equipAreas;
public List<vItem> items
{
get
{
if (GetItemsHandler != null)
{
return GetItemsHandler();
}
return new List<vItem>();
}
}
public List<vItem> allItems
{
get
{
if (GetItemsAllHandler != null)
{
return GetItemsAllHandler();
}
return new List<vItem>();
}
}
private float originalTimeScale = 1f;
private bool updatedTimeScale;
private vEquipArea currentEquipArea;
private StandaloneInputModule inputModule;
#endregion
protected virtual void Start()
{
// manage if you can equip a item or not
canEquip = true;
// search for a StandaloneInputModule in the scene
inputModule = FindObjectOfType<StandaloneInputModule>();
// if there is none, a new EventSystem is created
if (inputModule == null)
{
inputModule = (new GameObject("EventSystem")).AddComponent<StandaloneInputModule>();
}
// get equipAreas in this Inventory
equipAreas = GetComponentsInChildren<vEquipArea>(true);
// initialize every equipArea
foreach (vEquipArea equipArea in equipAreas)
{
equipArea.Init();
equipArea.onEquipItem.AddListener(OnEquipItem);
equipArea.onUnequipItem.AddListener(OnUnequipItem);
equipArea.onSelectEquipArea.AddListener(SetCurrentSelectedArea);
equipArea.onChangeEquipSlot.AddListener(ChangeEquipmentDisplay);
}
for (int i = 0; i < changeEquipmentControllers.Count; i++)
{
if (changeEquipmentControllers[i] != null && changeEquipmentControllers[i].equipArea && changeEquipmentControllers[i].display)
{
changeEquipmentControllers[i].equipArea.onSetLockToEquip.AddListener(changeEquipmentControllers[i].display.SetLockToEquip);
}
}
}
protected virtual void LateUpdate()
{
if (IsLocked())
{
return;
}
OpenCloseInventoryInput();
if (isOpen)
{
UpdateEventSystemInput();
}
if (!isOpen)
{
ChangeEquipmentInput();
}
else
{
RemoveEquipmentInput();
}
}
/// <summary>
/// This is just an example of saving the current items <seealso cref="vSaveLoadInventory"/>
/// </summary>
public virtual void SaveItemsExample()
{
var _itemManager = GetComponentInParent<vItemManager>();
_itemManager.SaveInventory();
}
/// <summary>
/// This is just an example of loading the saved items <seealso cref="vSaveLoadInventory"/>
/// </summary>
public virtual void LoadItemsExample()
{
var _itemManager = GetComponentInParent<vItemManager>();
_itemManager.LoadInventory();
}
public virtual void OnReloadGame()
{
StartCoroutine(ReloadEquipment());
}
protected virtual IEnumerator ReloadEquipment()
{
yield return new WaitForEndOfFrame();
inputModule = FindObjectOfType<StandaloneInputModule>();
isOpen = true;
for (int i = 0; i < equipAreas.Length; i++)
{
var equipArea = equipAreas[i];
for (int a = 0; a < equipArea.equipSlots.Count; a++)
{
var slot = equipArea.equipSlots[a];
if (equipArea.currentEquippedItem == null)
{
OnUnequipItem(equipArea, slot.item);
equipArea.UnequipItem(slot);
}
else
{
equipArea.UnequipItem(slot);
}
}
}
isOpen = false;
}
/// <summary>
/// Check if the Inventory Input is Locked
/// </summary>
/// <returns></returns>
public virtual bool IsLocked()
{
var _locked = (IsLockedEvent != null ? IsLockedEvent.Invoke() : false);
return _locked || lockInventoryInput;
}
public virtual void SetLockInventoryInput(bool value)
{
lockInventoryInput = value;
}
/// <summary>
/// Update all Inventory elements
/// </summary>
public virtual void UpdateInventory()
{
OnUpdateInventory?.Invoke();
onUpdateInventory.Invoke();
}
/// <summary>
/// Manage the input to open or close the Inventory
/// </summary>
public virtual void OpenCloseInventoryInput()
{
if (openInventory.GetButtonDown() && canEquip)
{
if (!isOpen)
{
OpenInventory();
}
else
{
CloseInventory();
}
}
}
/// <summary>
/// Open the Inventory Window
/// </summary>
public virtual void OpenInventory()
{
if (isOpen)
{
return;
}
isOpen = true;
if (!updatedTimeScale)
{
updatedTimeScale = true;
originalTimeScale = Time.timeScale;
Time.timeScale = timeScaleWhileIsOpen;
}
onOpenCloseInventory.Invoke(true);
}
/// <summary>
/// Closes the Inventory Window
/// </summary>
public virtual void CloseInventory()
{
if (!isOpen)
{
return;
}
isOpen = false;
if (updatedTimeScale)
{
Time.timeScale = originalTimeScale;
updatedTimeScale = false;
}
onOpenCloseInventory.Invoke(false);
}
/// <summary>
/// Input Button to remove the current selected equipped Item
/// </summary>
protected virtual void RemoveEquipmentInput()
{
if (currentEquipArea != null && removeEquipment.GetButtonDown())
{
currentEquipArea.UnequipCurrentItem();
}
}
/// <summary>
/// Assign the EquipArea of the Slot that you're selected
/// </summary>
/// <param name="equipArea"></param>
protected virtual void SetCurrentSelectedArea(vEquipArea equipArea)
{
currentEquipArea = equipArea;
}
/// <summary>
/// Input to change the current equipSlot
/// </summary>
protected virtual void ChangeEquipmentInput()
{
// display equiped itens
if (changeEquipmentControllers.Count > 0 && canEquip)
{
foreach (ChangeEquipmentControl changeEquip in changeEquipmentControllers)
{
UseItemInput(changeEquip);
if (changeEquip.equipArea != null)
{
if (changeEquip.previousItemInput.GetButtonDown())
{
changeEquip.equipArea.PreviousEquipSlot();
}
else if (changeEquip.nextItemInput.GetButtonDown())
{
changeEquip.equipArea.NextEquipSlot();
}
}
}
}
}
/// <summary>
/// Check if the items of your inventory still exists
/// </summary>
public virtual void CheckEquipmentChanges()
{
for (int i = 0; i < equipAreas.Length; i++)
{
var equipArea = equipAreas[i];
for (int a = 0; a < equipArea.equipSlots.Count; a++)
{
var slot = equipArea.equipSlots[a];
if (slot.item != null && !items.Contains(slot.item))
{
equipArea.UnequipItem(slot);
var changeEquip = changeEquipmentControllers.Find(e => e.equipArea.Equals(equipArea));
if (changeEquip != null && changeEquip.display)
{
changeEquip.display.RemoveItem();
}
}
}
}
}
/// <summary>
/// Replace the default input of the EventSystem to a <seealso cref="vInput"/>
/// </summary>
protected virtual void UpdateEventSystemInput()
{
if (inputModule)
{
inputModule.horizontalAxis = horizontal.buttonName;
inputModule.verticalAxis = vertical.buttonName;
inputModule.submitButton = submit.buttonName;
inputModule.cancelButton = cancel.buttonName;
}
else
{
inputModule = FindObjectOfType<StandaloneInputModule>();
}
}
/// <summary>
/// Input to use a equipped and consumable Item
/// </summary>
/// <param name="changeEquip"></param>
protected virtual void UseItemInput(ChangeEquipmentControl changeEquip)
{
if (changeEquip.display != null && changeEquip.display.item != null && changeEquip.display.item.type == vItemType.Consumable)
{
if (changeEquip.useItemInput.GetButtonDown() && changeEquip.display.item.amount > 0)
{
OnUseItem(changeEquip.display.item);
}
}
}
/// <summary>
/// Event to trigger when using an Item
/// </summary>
/// <param name="item"></param>
internal virtual void OnUseItem(vItem item)
{
onUseItem.Invoke(item);
}
/// <summary>
/// Event to trigger when you destroy the item
/// </summary>
/// <param name="item"></param>
/// <param name="amount"></param>
internal virtual void OnDestroyItem(vItem item, int amount)
{
onDestroyItem.Invoke(item, amount);
CheckEquipmentChanges();
}
/// <summary>
/// Event to trigger when you drop the item
/// </summary>
/// <param name="item"></param>
/// <param name="amount"></param>
internal virtual void OnDropItem(vItem item, int amount)
{
onDropItem.Invoke(item, amount);
CheckEquipmentChanges();
}
/// <summary>
/// Event to trigger when you equip an Item
/// </summary>
/// <param name="equipArea"></param>
/// <param name="item"></param>
public virtual void OnEquipItem(vEquipArea equipArea, vItem item)
{
onEquipItem.Invoke(equipArea, item);
ChangeEquipmentDisplay(equipArea, equipArea.currentEquippedItem);
}
/// <summary>
/// Event to trigger when you unequip an Item
/// </summary>
/// <param name="equipArea"></param>
/// <param name="item"></param>
public virtual void OnUnequipItem(vEquipArea equipArea, vItem item)
{
onUnequipItem.Invoke(equipArea, item);
ChangeEquipmentDisplay(equipArea, equipArea.currentEquippedItem);
}
/// <summary>
/// Updates the <seealso cref="ChangeEquipmentControl.display"/>
/// </summary>
/// <param name="equipArea"></param>
/// <param name="item"></param>
protected virtual void ChangeEquipmentDisplay(vEquipArea equipArea, vItem item)
{
if (changeEquipmentControllers.Count > 0)
{
var changeEquipControl = changeEquipmentControllers.Find(changeEquip => changeEquip.equipArea != null &&
changeEquip.equipArea == equipArea && changeEquip.display != null);
if (changeEquipControl != null)
{
changeEquipControl.display.AddItem(item);
changeEquipControl.display.ItemIdentifier(changeEquipControl.equipArea.indexOfEquippedItem + 1, true);
// if (changeEquipControl.display.item == item)
// {
// changeEquipControl.display.RemoveItem();
// changeEquipControl.display.ItemIdentifier(changeEquipControl.equipArea.indexOfEquippedItem + 1, true);
// }
// else if (equipArea.currentEquippedItem == item)
// {
// changeEquipControl.display.AddItem(item);
// changeEquipControl.display.ItemIdentifier(changeEquipControl.equipArea.indexOfEquippedItem + 1, true);
// }
}
}
}
}
[System.Serializable]
public class ChangeEquipmentControl
{
public GenericInput useItemInput = new GenericInput("U", "Start", "Start");
public GenericInput previousItemInput = new GenericInput("LeftArrow", "D - Pad Horizontal", "D-Pad Horizontal");
public GenericInput nextItemInput = new GenericInput("RightArrow", "D - Pad Horizontal", "D-Pad Horizontal");
public vEquipArea equipArea;
public vEquipmentDisplay display;
}
}

View File

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

View File

@@ -0,0 +1,222 @@
using System.Collections.Generic;
using UnityEngine;
namespace Invector.vItemManager
{
[System.Serializable]
public partial class vItem : ScriptableObject
{
#region SerializedProperties in customEditor
[HideInInspector]
public int id;
[HideInInspector]
public string description = "Item Description";
[HideInInspector]
public vItemType type;
[HideInInspector]
public Sprite icon;
[HideInInspector]
public bool stackable = true;
[HideInInspector]
public bool createNewItem = true;
[HideInInspector]
public int maxStack;
[HideInInspector]
public int amount;
[HideInInspector]
public GameObject originalObject;
[HideInInspector]
public GameObject dropObject;
[HideInInspector]
public List<vItemAttribute> attributes = new List<vItemAttribute>();
[HideInInspector]
public bool isInEquipArea;
[HideInInspector]
public bool isEquiped;
#endregion
#region Properties in defaultInspector
public bool destroyAfterUse = true;
public bool canBeEquipped = true;
public bool canBeUsed = true;
public bool canBeDroped = true;
public bool canBeDestroyed = true;
[Header("Animation Settings")]
[vHelpBox("Triggers a animation when Equipping a Weapon or enabling item.\nYou can also trigger an animation if the ItemType is a Consumable")]
public string EnableAnim = "LowBack";
[vHelpBox("Triggers a animation when Unequipping a Weapon or disable item")]
public string DisableAnim = "LowBack";
[vHelpBox("Delay to enable the Weapon/Item object when Equipping\n If ItemType is a Consumable use this to delay the item usage.")]
public float enableDelayTime = 0.5f;
[vHelpBox("Delay to hide the Weapon/Item object when Unequipping")]
public float disableDelayTime = 0.5f;
[vHelpBox("If the item is equippable use this to set a custom handler to instantiate the SpawnObject")]
public string customHandler;
[vHelpBox("If the item is equippable and need to use two hand\n<color=yellow><b>This option makes it impossible to equip two items</b></color>")]
public bool twoHandWeapon;
[HideInInspector]
public OnHandleItemEvent onDestroy;
#endregion
public void OnDestroy()
{
onDestroy.Invoke(this);
}
/// <summary>
/// Convert Sprite icon to texture
/// </summary>
public Texture2D iconTexture
{
get
{
if (!icon) return null;
try
{
if (icon.rect.width != icon.texture.width || icon.rect.height != icon.texture.height)
{
Texture2D newText = new Texture2D((int)icon.textureRect.width, (int)icon.textureRect.height);
newText.name = icon.name;
Color[] newColors = icon.texture.GetPixels((int)icon.textureRect.x, (int)icon.textureRect.y, (int)icon.textureRect.width, (int)icon.textureRect.height);
newText.SetPixels(newColors);
newText.Apply();
return newText;
}
else
return icon.texture;
}
catch
{
Debug.LogWarning("Icon texture of the " + name + " is not Readable", icon.texture);
return icon.texture;
}
}
}
/// <summary>
/// Get the Item Attribute via <seealso cref="vItemAttribute"/>
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public vItemAttribute GetItemAttribute(vItemAttributes attribute)
{
if (attributes != null) return attributes.Find(_attribute => _attribute.name == attribute);
return null;
}
/// <summary>
/// Get the Item Attribute via string
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public vItemAttribute GetItemAttribute(string name)
{
if (attributes != null)
return attributes.Find(attribute => attribute.name.ToString().Equals(name));
return null;
}
/// <summary>
/// Get Selected Item Attributes via <seealso cref="vItemAttribute"/> by ignoring the ones you don't want
/// </summary>
/// <param name="ignore"></param>
/// <returns></returns>
public string GetItemAttributesText(List<vItemAttributes> ignore = null)
{
System.Text.StringBuilder text = new System.Text.StringBuilder();
for (int i = 0; i < attributes.Count; i++)
{
if (ignore == null || !ignore.Contains(attributes[i].name))
text.AppendLine(GetItemAttributeText(i));
}
return text.ToString();
}
/// <summary>
/// Get Item Attribute Text
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
protected string GetItemAttributeText(int i)
{
if (attributes.Count > 0 && i < attributes.Count)
{
if (attributes.Count > 0 && i < attributes.Count)
{
return attributes[i].GetDisplayText();
}
}
return string.Empty;
}
/// <summary>
/// Get Item Attribut Text with a custom Format to display
/// </summary>
/// <param name="i"></param>
/// <param name="customFormat"></param>
/// <returns></returns>
protected string GetItemAttributeText(int i, string customFormat)
{
if (attributes.Count > 0 && i < attributes.Count)
{
return attributes[i].GetDisplayText(customFormat);
}
return string.Empty;
}
/// <summary>
/// Get Default Item type text
/// </summary>
/// <returns></returns>
public string ItemTypeText()
{
return ItemTypeText(type.DisplayFormat());
}
/// <summary>
/// Get Custom Item type text
/// </summary>
/// <param name="format"> Custom format for text </param>
/// <returns></returns>
public string ItemTypeText(string format)
{
var _text = format;
var value = type.ToString().InsertSpaceBeforeUpperCase().RemoveUnderline();
if (string.IsNullOrEmpty(_text))
return value;
else if (_text.Contains("(NAME)")) _text.Replace("(NAME)", value);
return _text;
}
/// <summary>
/// Get Item Full Description text including item Name, Type, Description and Attributes
/// </summary>
/// <param name="format">Custom format</param>
/// <param name="ignoreAttributes">Attributes to ignore</param>
/// <returns></returns>
public string GetFullItemDescription(string format = null, List<vItemAttributes> ignoreAttributes = null)
{
string text = "";
if (string.IsNullOrEmpty(format))
{
text += (name);
text += "\n" + (ItemTypeText());
text += "\n" + (description);
text += "\n" + (GetItemAttributesText());
}
else
{
text = format;
if (text.Contains("(NAME)")) text = text.Replace("(NAME)", name);
if (text.Contains("(TYPE)")) text = text.Replace("(TYPE)", ItemTypeText());
if (text.Contains("(DESC)")) text = text.Replace("(DESC)", description);
if (text.Contains("(ATTR)")) text = text.Replace("(ATTR)", GetItemAttributesText(ignoreAttributes));
}
return text;
}
}
}

View File

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

View File

@@ -0,0 +1,39 @@
using UnityEngine;
using UnityEngine.UI;
namespace Invector.vItemManager
{
public class vItemAmountWindow : vMasterWindow
{
public vItemWindowDisplay itemWindowDisplay;
public GameObject singleAmountControl;
public GameObject multAmountControl;
public Text amountDisplay;
protected override void OnEnable()
{
base.OnEnable();
if (itemWindowDisplay)
{
if (itemWindowDisplay.currentSelectedSlot.item)
{
singleAmountControl.SetActive(!(itemWindowDisplay.currentSelectedSlot.item.amount > 1));
multAmountControl.SetActive(itemWindowDisplay.currentSelectedSlot.item.amount > 1);
if (amountDisplay)
amountDisplay.text = (1).ToString("00");
itemWindowDisplay.amount = 1;
}
}
}
public virtual void ChangeAmount(int value)
{
if (itemWindowDisplay && itemWindowDisplay.currentSelectedSlot.item)
{
itemWindowDisplay.amount += value;
itemWindowDisplay.amount = Mathf.Clamp(itemWindowDisplay.amount, 1, itemWindowDisplay.currentSelectedSlot.item.amount);
if (amountDisplay)
amountDisplay.text = itemWindowDisplay.amount.ToString("00");
}
}
}
}

View File

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

View File

@@ -0,0 +1,99 @@
using System.Collections.Generic;
namespace Invector.vItemManager
{
/// <summary>
/// Attribute of the item including the value (int)
/// </summary>
[System.Serializable]
public class vItemAttribute
{
public vItemAttributes name = 0;
public int value = 0;
public bool isOpen;
public bool isBool;
public string displayFormat
{
get
{
return name.DisplayFormat();
}
}
/// <summary>
/// Get attribute text
/// </summary>
/// <param name="format">custom format, if null, the format will be <seealso cref=" displayFormat"/></param>
/// <returns>Formated attribute text</returns>
public string GetDisplayText(string format = null)
{
{
var _text = string.IsNullOrEmpty(format) ? displayFormat : format;
if (string.IsNullOrEmpty(_text))
{
_text = name.ToString().InsertSpaceBeforeUpperCase().RemoveUnderline();
_text += " : " + value.ToString();
}
else
{
if (_text.Contains("(NAME)"))
{
_text = _text.Replace("(NAME)", name.ToString().InsertSpaceBeforeUpperCase().RemoveUnderline());
}
if (_text.Contains("(VALUE)"))
{
_text = _text.Replace("(VALUE)", value.ToString());
}
}
return _text;
}
}
public vItemAttribute(vItemAttributes name, int value)
{
this.name = name;
this.value = value;
}
}
public static class vItemAttributeHelper
{
public static void CopyTo(this vItemAttribute itemAttribute, vItemAttribute to)
{
to.isBool = itemAttribute.isBool;
to.name = itemAttribute.name;
to.value = itemAttribute.value;
}
public static bool Contains(this List<vItemAttribute> attributes, vItemAttributes name)
{
var attribute = attributes.Find(at => at.name == name);
return attribute != null;
}
public static vItemAttribute GetAttributeByType(this List<vItemAttribute> attributes, vItemAttributes name)
{
var attribute = attributes.Find(at => at.name == name);
return attribute;
}
public static bool Equals(this vItemAttribute attributeA, vItemAttribute attributeB)
{
return attributeA.name == attributeB.name;
}
public static List<vItemAttribute> CopyAsNew(this List<vItemAttribute> copy)
{
var target = new List<vItemAttribute>();
if (copy != null)
{
for (int i = 0; i < copy.Count; i++)
{
vItemAttribute attribute = new vItemAttribute(copy[i].name, copy[i].value);
target.Add(attribute);
}
}
return target;
}
}
}

View File

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

View File

@@ -0,0 +1,10 @@
using UnityEngine;
using System.Collections.Generic;
namespace Invector
{
public class vItemAttributes : ScriptableObject
{
public List<string> attributes = new List<string>();
}
}

View File

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

View File

@@ -0,0 +1,32 @@
using UnityEngine;
using System.Collections.Generic;
namespace Invector.vItemManager
{
using vCharacterController.vActions;
public class vItemCollection : vTriggerGenericAction
{
[vEditorToolbar("Item Collection")]
[Header("--- Item Collection Options ---")]
[Tooltip("List of items you want to use")]
public vItemListData itemListData;
[Tooltip("Delay to actually collect the items, you can use to match with animations of getting the item")]
public float onCollectDelay;
[Tooltip("Drag and drop the prefab ItemCollectionDisplay inside the UI gameObject to show a text of the items you've collected")]
public float textDelay = 0.25f;
[Tooltip("Ignore the Enable/Disable animation of your item, you can assign an animation to your item in the ItemListData")]
public bool ignoreItemAnimation = false;
[HideInInspector]
public List<vItemType> itemsFilter = new List<vItemType>() { 0 };
[HideInInspector]
public List<ItemReference> items = new List<ItemReference>();
protected override void Start()
{
base.Start();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ae518b3558fb3934d9483114512189ea
timeCreated: 1548187086
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 65f0ab239a5cfe64897f8b4b02466643, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,39 @@
using UnityEngine;
namespace Invector.vItemManager
{
[vClassHeader("Item Collected Display", helpBoxText = "Use this to display the name of collected items", openClose = false)]
public class vItemCollectionDisplay : vMonoBehaviour
{
private static vItemCollectionDisplay instance;
/// <summary>
/// Instance of the <seealso cref="vItemCollectionDisplay"/>
/// </summary>
///
public static vItemCollectionDisplay Instance
{
get
{
if (instance == null) { instance = GameObject.FindObjectOfType<vItemCollectionDisplay>(); }
return vItemCollectionDisplay.instance;
}
}
public vItemCollectionTextHUD itemCollectedDiplayPrefab;
/// <summary>
/// Send text to display in the HUD with fade in <seealso cref="vItemCollectionTextHUD"/>
/// </summary>
/// <param name="message">message to show</param>
/// <param name="timeToStay">time to stay showing</param>
/// <param name="timeToFadeOut">time to fade out</param>
public virtual void FadeText(string message, float timeToStay, float timeToFadeOut)
{
var display = Instantiate(itemCollectedDiplayPrefab);
display.transform.SetParent(transform, false);
display.transform.SetAsFirstSibling();
display.Show(message, timeToStay, timeToFadeOut);
}
}
}

View File

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

View File

@@ -0,0 +1,24 @@
using UnityEngine;
namespace Invector.vItemManager
{
public class vItemCollectionDisplay_v2 : MonoBehaviour
{
public vItemManager itemManager;
public vItemDisplay displayPrefab;
public RectTransform content;
public float displayTime = 3f;
protected virtual void Start()
{
itemManager.onCollectItem.AddListener(OnAddItem);
}
protected virtual void OnAddItem(vItemManager.CollectedItemInfo info)
{
var display = Instantiate(displayPrefab);
display.transform.SetParent(content, false);
display.DisplayItem(info);
display.transform.SetAsFirstSibling();
Destroy(display.gameObject, displayTime);
}
}
}

View File

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

View File

@@ -0,0 +1,49 @@
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace Invector.vItemManager
{
[vClassHeader("Item Collection HUD", helpBoxText = "Contains all behaviour to show messages sended")]
public class vItemCollectionTextHUD : MonoBehaviour
{
public Text Message;
/// <summary>
/// Show a Message on the HUD
/// </summary>
/// <param name="message">message to show</param>
/// <param name="timeToStay">time to stay showing</param>
/// <param name="timeToFadeOut">time to fade out</param>
public void Show(string message, float timeToStay = 1, float timeToFadeOut = 1)
{
Message.text = message;
StartCoroutine(Timer(timeToStay, timeToFadeOut));
}
IEnumerator Timer(float timeToStay = 1, float timeToFadeOut = 1)
{
Message.CrossFadeAlpha(1, 0.5f, false);
yield return new WaitForSeconds(timeToStay);
Message.CrossFadeAlpha(0, timeToFadeOut, false);
yield return new WaitForSeconds(timeToFadeOut + 0.1f);
Destroy(gameObject);
}
private void Awake()
{
Clear();
}
/// <summary>
/// Clear message text display
/// </summary>
///
public void Clear()
{
Message.text = "";
Message.CrossFadeAlpha(0, 0, false);
}
}
}

View File

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

View File

@@ -0,0 +1,64 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Invector.vItemManager
{
[vClassHeader("vItemDisplay")]
public class vItemDisplay : vMonoBehaviour
{
[vEditorToolbar("Settings")]
public Image icon;
public Text itemName;
public Text type;
public Text amount;
[vEditorToolbar("ColorByType")]
public bool useColorByType;
public MaskableGraphic bgColor;
public ColorByType[] colorByTypes;
[System.Serializable]
public class ColorByType
{
public List<vItemType> types;
public Color color = Color.white;
public ColorByType()
{
Color color = Color.white;
}
}
[vHelpBox("Use {0} inside string format to inset the value")]
public string nameFormat = "Name: {0}";
public string typeFormat = "Type: {0}";
public string amountFormat = "Amount: {0}";
public bool displayAmountOnlyGreaterOne = true;
public virtual void DisplayItem(vItemManager.CollectedItemInfo info)
{
if (useColorByType)
{
var colorType = System.Array.Find(colorByTypes, c => c.types.Contains(info.item.type));
if (colorType != null)
bgColor.color = colorType.color;
}
icon.sprite = info.item.icon;
itemName.text = FormatText(nameFormat, info.item.name);
type.text = FormatText(typeFormat, info.item.type.ToString());
if (info.amount > 1 || !displayAmountOnlyGreaterOne)
{
amount.text = FormatText(amountFormat, info.amount.ToString());
}
else amount.text = "";
}
public virtual string FormatText(string format, string value)
{
if (string.IsNullOrEmpty(format)) return value;
return string.Format(format, value);
}
}
}

View File

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

View File

@@ -0,0 +1,35 @@
using Invector.vItemManager;
using System.Collections.Generic;
using UnityEngine;
public class vItemDisplay3D : MonoBehaviour
{
[System.Serializable]
public class vDisplay
{
public int itemId;
public GameObject itemModel;
}
public GameObject currentItemModel;
public List<vDisplay> displays;
public virtual void Display(vItemSlot slot)
{
if (slot) Display(slot.item);
}
public virtual void Display(int id)
{
vDisplay display = displays.Find(d => d.itemId.Equals(id));
if (display != null)
{
if (currentItemModel) currentItemModel.SetActive(false);
display.itemModel.SetActive(true);
currentItemModel = display.itemModel;
}
}
public virtual void Display(vItem item)
{
if (item) Display(item.id);
}
}

View File

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

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: be7525468303b0d47bcb659cc944bc5a
folderAsset: yes
timeCreated: 1487728733
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 2663967159f2ded49a7138ca8a6390d1
folderAsset: yes
timeCreated: 1487728749
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More