This commit is contained in:
2020-07-04 14:41:25 +08:00
parent 70c346d2c1
commit a8f02e4da5
3748 changed files with 587372 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: de8aa54045770a84ab93ebe04831dcba
folderAsset: yes
timeCreated: 1516240530
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 19efe962ed720b24e94743b984aad16b
folderAsset: yes
timeCreated: 1516240530
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,399 @@
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit Inventory Databases.
/// </summary>
[CustomEditor(typeof(InvDatabase))]
public class InvDatabaseInspector : Editor
{
static int mIndex = 0;
bool mConfirmDelete = false;
/// <summary>
/// Draw an enlarged sprite within the specified texture atlas.
/// </summary>
public Rect DrawSprite (Texture2D tex, Rect sprite, Material mat) { return DrawSprite(tex, sprite, mat, true, 0); }
/// <summary>
/// Draw an enlarged sprite within the specified texture atlas.
/// </summary>
public Rect DrawSprite (Texture2D tex, Rect sprite, Material mat, bool addPadding)
{
return DrawSprite(tex, sprite, mat, addPadding, 0);
}
/// <summary>
/// Draw an enlarged sprite within the specified texture atlas.
/// </summary>
public Rect DrawSprite (Texture2D tex, Rect sprite, Material mat, bool addPadding, int maxSize)
{
float paddingX = addPadding ? 4f / tex.width : 0f;
float paddingY = addPadding ? 4f / tex.height : 0f;
float ratio = (sprite.height + paddingY) / (sprite.width + paddingX);
ratio *= (float)tex.height / tex.width;
// Draw the checkered background
Color c = GUI.color;
Rect rect = NGUIEditorTools.DrawBackground(tex, ratio);
GUI.color = c;
if (maxSize > 0)
{
float dim = maxSize / Mathf.Max(rect.width, rect.height);
rect.width *= dim;
rect.height *= dim;
}
// We only want to draw into this rectangle
if (Event.current.type == EventType.Repaint)
{
if (mat == null)
{
GUI.DrawTextureWithTexCoords(rect, tex, sprite);
}
else
{
// NOTE: DrawPreviewTexture doesn't seem to support BeginGroup-based clipping
// when a custom material is specified. It seems to be a bug in Unity.
// Passing 'null' for the material or omitting the parameter clips as expected.
UnityEditor.EditorGUI.DrawPreviewTexture(sprite, tex, mat);
//UnityEditor.EditorGUI.DrawPreviewTexture(drawRect, tex);
//GUI.DrawTexture(drawRect, tex);
}
rect = new Rect(sprite.x + rect.x, sprite.y + rect.y, sprite.width, sprite.height);
}
return rect;
}
/// <summary>
/// Helper function that sets the index to the index of the specified item.
/// </summary>
public static void SelectIndex (InvDatabase db, InvBaseItem item)
{
mIndex = 0;
foreach (InvBaseItem i in db.items)
{
if (i == item) break;
++mIndex;
}
}
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
InvDatabase db = target as InvDatabase;
NGUIEditorTools.DrawSeparator();
InvBaseItem item = null;
if (db.items == null || db.items.Count == 0)
{
mIndex = 0;
}
else
{
mIndex = Mathf.Clamp(mIndex, 0, db.items.Count - 1);
item = db.items[mIndex];
}
if (mConfirmDelete)
{
// Show the confirmation dialog
GUILayout.Label("Are you sure you want to delete '" + item.name + "'?");
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
{
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Cancel")) mConfirmDelete = false;
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Delete"))
{
NGUIEditorTools.RegisterUndo("Delete Inventory Item", db);
db.items.RemoveAt(mIndex);
mConfirmDelete = false;
}
GUI.backgroundColor = Color.white;
}
GUILayout.EndHorizontal();
}
else
{
// Database icon atlas
UIAtlas atlas = EditorGUILayout.ObjectField("Icon Atlas", db.iconAtlas, typeof(UIAtlas), false) as UIAtlas;
if (atlas != db.iconAtlas)
{
NGUIEditorTools.RegisterUndo("Databse Atlas change", db);
db.iconAtlas = atlas;
foreach (InvBaseItem i in db.items) i.iconAtlas = atlas;
}
// Database ID
int dbID = EditorGUILayout.IntField("Database ID", db.databaseID);
if (dbID != db.databaseID)
{
NGUIEditorTools.RegisterUndo("Database ID change", db);
db.databaseID = dbID;
}
// "New" button
GUI.backgroundColor = Color.green;
if (GUILayout.Button("New Item"))
{
NGUIEditorTools.RegisterUndo("Add Inventory Item", db);
InvBaseItem bi = new InvBaseItem();
bi.iconAtlas = db.iconAtlas;
bi.id16 = (db.items.Count > 0) ? db.items[db.items.Count - 1].id16 + 1 : 0;
db.items.Add(bi);
mIndex = db.items.Count - 1;
if (item != null)
{
bi.name = "Copy of " + item.name;
bi.description = item.description;
bi.slot = item.slot;
bi.color = item.color;
bi.iconName = item.iconName;
bi.attachment = item.attachment;
bi.minItemLevel = item.minItemLevel;
bi.maxItemLevel = item.maxItemLevel;
foreach (InvStat stat in item.stats)
{
InvStat copy = new InvStat();
copy.id = stat.id;
copy.amount = stat.amount;
copy.modifier = stat.modifier;
bi.stats.Add(copy);
}
}
else
{
bi.name = "New Item";
bi.description = "Item Description";
}
item = bi;
}
GUI.backgroundColor = Color.white;
if (item != null)
{
NGUIEditorTools.DrawSeparator();
// Navigation section
GUILayout.BeginHorizontal();
{
if (mIndex == 0) GUI.color = Color.grey;
if (GUILayout.Button("<<")) { mConfirmDelete = false; --mIndex; }
GUI.color = Color.white;
mIndex = EditorGUILayout.IntField(mIndex + 1, GUILayout.Width(40f)) - 1;
GUILayout.Label("/ " + db.items.Count, GUILayout.Width(40f));
if (mIndex + 1 == db.items.Count) GUI.color = Color.grey;
if (GUILayout.Button(">>")) { mConfirmDelete = false; ++mIndex; }
GUI.color = Color.white;
}
GUILayout.EndHorizontal();
NGUIEditorTools.DrawSeparator();
// Item name and delete item button
GUILayout.BeginHorizontal();
{
string itemName = EditorGUILayout.TextField("Item Name", item.name);
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Delete", GUILayout.Width(55f)))
{
mConfirmDelete = true;
}
GUI.backgroundColor = Color.white;
if (!itemName.Equals(item.name))
{
NGUIEditorTools.RegisterUndo("Rename Item", db);
item.name = itemName;
}
}
GUILayout.EndHorizontal();
string itemDesc = GUILayout.TextArea(item.description, 200, GUILayout.Height(100f));
InvBaseItem.Slot slot = (InvBaseItem.Slot)EditorGUILayout.EnumPopup("Slot", item.slot);
string iconName = "";
float iconSize = 64f;
bool drawIcon = false;
float extraSpace = 0f;
if (item.iconAtlas != null)
{
BetterList<string> sprites = item.iconAtlas.GetListOfSprites();
sprites.Insert(0, "<None>");
int index = 0;
string spriteName = (item.iconName != null) ? item.iconName : sprites[0];
// We need to find the sprite in order to have it selected
if (!string.IsNullOrEmpty(spriteName))
{
for (int i = 1; i < sprites.size; ++i)
{
if (spriteName.Equals(sprites[i], System.StringComparison.OrdinalIgnoreCase))
{
index = i;
break;
}
}
}
// Draw the sprite selection popup
index = EditorGUILayout.Popup("Icon", index, sprites.ToArray());
UISpriteData sprite = (index > 0) ? item.iconAtlas.GetSprite(sprites[index]) : null;
if (sprite != null)
{
iconName = sprite.name;
Material mat = item.iconAtlas.spriteMaterial;
if (mat != null)
{
Texture2D tex = mat.mainTexture as Texture2D;
if (tex != null)
{
drawIcon = true;
Rect rect = new Rect(sprite.x, sprite.y, sprite.width, sprite.height);
rect = NGUIMath.ConvertToTexCoords(rect, tex.width, tex.height);
GUILayout.Space(4f);
GUILayout.BeginHorizontal();
{
GUILayout.Space(Screen.width - iconSize);
DrawSprite(tex, rect, null, false);
}
GUILayout.EndHorizontal();
extraSpace = iconSize * (float)sprite.height / sprite.width;
}
}
}
}
// Item level range
GUILayout.BeginHorizontal();
GUILayout.Label("Level Range", GUILayout.Width(77f));
int min = EditorGUILayout.IntField(item.minItemLevel, GUILayout.MinWidth(40f));
int max = EditorGUILayout.IntField(item.maxItemLevel, GUILayout.MinWidth(40f));
if (drawIcon) GUILayout.Space(iconSize);
GUILayout.EndHorizontal();
// Game Object attachment field, left of the icon
GUILayout.BeginHorizontal();
GameObject go = (GameObject)EditorGUILayout.ObjectField("Attachment", item.attachment, typeof(GameObject), false);
if (drawIcon) GUILayout.Space(iconSize);
GUILayout.EndHorizontal();
// Color tint field, left of the icon
GUILayout.BeginHorizontal();
Color color = EditorGUILayout.ColorField("Color", item.color);
if (drawIcon) GUILayout.Space(iconSize);
GUILayout.EndHorizontal();
// Calculate the extra spacing necessary for the icon to show up properly and not overlap anything
if (drawIcon)
{
extraSpace = Mathf.Max(0f, extraSpace - 60f);
GUILayout.Space(extraSpace);
}
// Item stats
NGUIEditorTools.DrawSeparator();
if (item.stats != null)
{
for (int i = 0; i < item.stats.Count; ++i)
{
InvStat stat = item.stats[i];
GUILayout.BeginHorizontal();
{
InvStat.Identifier iden = (InvStat.Identifier)EditorGUILayout.EnumPopup(stat.id, GUILayout.Width(80f));
// Color the field red if it's negative, green if it's positive
if (stat.amount > 0) GUI.backgroundColor = Color.green;
else if (stat.amount < 0) GUI.backgroundColor = Color.red;
int amount = EditorGUILayout.IntField(stat.amount, GUILayout.Width(40f));
GUI.backgroundColor = Color.white;
InvStat.Modifier mod = (InvStat.Modifier)EditorGUILayout.EnumPopup(stat.modifier);
GUI.backgroundColor = Color.red;
if (GUILayout.Button("X", GUILayout.Width(20f)))
{
NGUIEditorTools.RegisterUndo("Delete Item Stat", db);
item.stats.RemoveAt(i);
--i;
}
else if (iden != stat.id || amount != stat.amount || mod != stat.modifier)
{
NGUIEditorTools.RegisterUndo("Item Stats", db);
stat.id = iden;
stat.amount = amount;
stat.modifier = mod;
}
GUI.backgroundColor = Color.white;
}
GUILayout.EndHorizontal();
}
}
if (GUILayout.Button("Add Stat", GUILayout.Width(80f)))
{
NGUIEditorTools.RegisterUndo("Add Item Stat", db);
InvStat stat = new InvStat();
stat.id = InvStat.Identifier.Armor;
item.stats.Add(stat);
}
// Save all values
if (!itemDesc.Equals(item.description) ||
slot != item.slot ||
go != item.attachment ||
color != item.color ||
min != item.minItemLevel ||
max != item.maxItemLevel ||
!iconName.Equals(item.iconName))
{
NGUIEditorTools.RegisterUndo("Item Properties", db);
item.description = itemDesc;
item.slot = slot;
item.attachment = go;
item.color = color;
item.iconName = iconName;
item.minItemLevel = min;
item.maxItemLevel = max;
}
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1a4e623d2eabebb4e8f6296a5fee1116
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,192 @@
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Inventory System search functionality.
/// </summary>
public class InvFindItem : ScriptableWizard
{
/// <summary>
/// Private class used to return data from the Find function below.
/// </summary>
struct FindResult
{
public InvDatabase db;
public InvBaseItem item;
}
string mItemName = "";
List<FindResult> mResults = new List<FindResult>();
/// <summary>
/// Add a menu option to display this wizard.
/// </summary>
[MenuItem("Window/Find Item #&i")]
static void FindItem ()
{
ScriptableWizard.DisplayWizard<InvFindItem>("Find Item");
}
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
string newItemName = EditorGUILayout.TextField("Search for:", mItemName);
NGUIEditorTools.DrawSeparator();
if (GUI.changed || newItemName != mItemName)
{
mItemName = newItemName;
if (string.IsNullOrEmpty(mItemName))
{
mResults.Clear();
}
else
{
FindAllByName(mItemName);
}
}
if (mResults.Count == 0)
{
if (!string.IsNullOrEmpty(mItemName))
{
GUILayout.Label("No matches found");
}
}
else
{
Print3("Item ID", "Item Name", "Path", false);
NGUIEditorTools.DrawSeparator();
foreach (FindResult fr in mResults)
{
if (Print3(InvDatabase.FindItemID(fr.item).ToString(),
fr.item.name, NGUITools.GetHierarchy(fr.db.gameObject), true))
{
InvDatabaseInspector.SelectIndex(fr.db, fr.item);
Selection.activeGameObject = fr.db.gameObject;
EditorUtility.SetDirty(Selection.activeGameObject);
}
}
}
}
/// <summary>
/// Helper function used to print things in columns.
/// </summary>
bool Print3 (string a, string b, string c, bool button)
{
bool retVal = false;
GUILayout.BeginHorizontal();
{
GUILayout.Label(a, GUILayout.Width(80f));
GUILayout.Label(b, GUILayout.Width(160f));
GUILayout.Label(c);
if (button)
{
retVal = GUILayout.Button("Select", GUILayout.Width(60f));
}
else
{
GUILayout.Space(60f);
}
}
GUILayout.EndHorizontal();
return retVal;
}
/// <summary>
/// Find items by name.
/// </summary>
void FindAllByName (string partial)
{
partial = partial.ToLower();
mResults.Clear();
// Exact match comes first
foreach (InvDatabase db in InvDatabase.list)
{
foreach (InvBaseItem item in db.items)
{
if (item.name.Equals(partial, System.StringComparison.OrdinalIgnoreCase))
{
FindResult fr = new FindResult();
fr.db = db;
fr.item = item;
mResults.Add(fr);
}
}
}
// Next come partial matches that begin with the specified string
foreach (InvDatabase db in InvDatabase.list)
{
foreach (InvBaseItem item in db.items)
{
if (item.name.StartsWith(partial, System.StringComparison.OrdinalIgnoreCase))
{
bool exists = false;
foreach (FindResult res in mResults)
{
if (res.item == item)
{
exists = true;
break;
}
}
if (!exists)
{
FindResult fr = new FindResult();
fr.db = db;
fr.item = item;
mResults.Add(fr);
}
}
}
}
// Other partial matches come last
foreach (InvDatabase db in InvDatabase.list)
{
foreach (InvBaseItem item in db.items)
{
if (item.name.ToLower().Contains(partial))
{
bool exists = false;
foreach (FindResult res in mResults)
{
if (res.item == item)
{
exists = true;
break;
}
}
if (!exists)
{
FindResult fr = new FindResult();
fr.db = db;
fr.item = item;
mResults.Add(fr);
}
}
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5d433ff63a7db764b8e246e67a296dc8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 64bcea337c8d18f4a9055c56dc45e63e
folderAsset: yes
timeCreated: 1516240530
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,46 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Equip the specified items on the character when the script is started.
/// </summary>
[AddComponentMenu("NGUI/Examples/Equip Items")]
public class EquipItems : MonoBehaviour
{
public int[] itemIDs;
void Start ()
{
if (itemIDs != null && itemIDs.Length > 0)
{
InvEquipment eq = GetComponent<InvEquipment>();
if (eq == null) eq = gameObject.AddComponent<InvEquipment>();
int qualityLevels = (int)InvGameItem.Quality._LastDoNotUse;
for (int i = 0, imax = itemIDs.Length; i < imax; ++i)
{
int index = itemIDs[i];
InvBaseItem item = InvDatabase.FindByID(index);
if (item != null)
{
InvGameItem gi = new InvGameItem(index, item);
gi.quality = (InvGameItem.Quality)Random.Range(0, qualityLevels);
gi.itemLevel = NGUITools.RandomRange(item.minItemLevel, item.maxItemLevel);
eq.Equip(gi);
}
else
{
Debug.LogWarning("Can't resolve the item ID of " + index);
}
}
}
Destroy(this);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cb5a46fe53751ae41980843a556d012e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,33 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Create and equip a random item on the specified target.
/// </summary>
[AddComponentMenu("NGUI/Examples/Equip Random Item")]
public class EquipRandomItem : MonoBehaviour
{
public InvEquipment equipment;
void OnClick()
{
if (equipment == null) return;
List<InvBaseItem> list = InvDatabase.list[0].items;
if (list.Count == 0) return;
int qualityLevels = (int)InvGameItem.Quality._LastDoNotUse;
int index = Random.Range(0, list.Count);
InvBaseItem item = list[index];
InvGameItem gi = new InvGameItem(index, item);
gi.quality = (InvGameItem.Quality)Random.Range(0, qualityLevels);
gi.itemLevel = NGUITools.RandomRange(item.minItemLevel, item.maxItemLevel);
equipment.Equip(gi);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 646fca1f4356ca24e9cee27b0432ab47
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,118 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Selectable sprite that follows the mouse.
/// </summary>
[RequireComponent(typeof(UISprite))]
[AddComponentMenu("NGUI/Examples/UI Cursor")]
public class UICursor : MonoBehaviour
{
static public UICursor instance;
// Camera used to draw this cursor
public Camera uiCamera;
Transform mTrans;
UISprite mSprite;
UIAtlas mAtlas;
string mSpriteName;
/// <summary>
/// Keep an instance reference so this class can be easily found.
/// </summary>
void Awake () { instance = this; }
void OnDestroy () { instance = null; }
/// <summary>
/// Cache the expected components and starting values.
/// </summary>
void Start ()
{
mTrans = transform;
mSprite = GetComponentInChildren<UISprite>();
if (uiCamera == null)
uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
if (mSprite != null)
{
mAtlas = mSprite.atlas;
mSpriteName = mSprite.spriteName;
if (mSprite.depth < 100) mSprite.depth = 100;
}
}
/// <summary>
/// Reposition the widget.
/// </summary>
void Update ()
{
Vector3 pos = Input.mousePosition;
if (uiCamera != null)
{
// Since the screen can be of different than expected size, we want to convert
// mouse coordinates to view space, then convert that to world position.
pos.x = Mathf.Clamp01(pos.x / Screen.width);
pos.y = Mathf.Clamp01(pos.y / Screen.height);
mTrans.position = uiCamera.ViewportToWorldPoint(pos);
// For pixel-perfect results
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
if (uiCamera.isOrthoGraphic)
#else
if (uiCamera.orthographic)
#endif
{
Vector3 lp = mTrans.localPosition;
lp.x = Mathf.Round(lp.x);
lp.y = Mathf.Round(lp.y);
mTrans.localPosition = lp;
}
}
else
{
// Simple calculation that assumes that the camera is of fixed size
pos.x -= Screen.width * 0.5f;
pos.y -= Screen.height * 0.5f;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
mTrans.localPosition = pos;
}
}
/// <summary>
/// Clear the cursor back to its original value.
/// </summary>
static public void Clear ()
{
if (instance != null && instance.mSprite != null)
Set(instance.mAtlas, instance.mSpriteName);
}
/// <summary>
/// Override the cursor with the specified sprite.
/// </summary>
static public void Set (UIAtlas atlas, string sprite)
{
if (instance != null && instance.mSprite)
{
instance.mSprite.atlas = atlas;
instance.mSprite.spriteName = sprite;
instance.mSprite.MakePixelPerfect();
instance.Update();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a60dfda9b1153fd4ca035013c64cf495
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,34 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// A UI script that keeps an eye on the slot in character equipment.
/// </summary>
[AddComponentMenu("NGUI/Examples/UI Equipment Slot")]
public class UIEquipmentSlot : UIItemSlot
{
public InvEquipment equipment;
public InvBaseItem.Slot slot;
override protected InvGameItem observedItem
{
get
{
return (equipment != null) ? equipment.GetItem(slot) : null;
}
}
/// <summary>
/// Replace the observed item with the specified value. Should return the item that was replaced.
/// </summary>
override protected InvGameItem Replace (InvGameItem item)
{
return (equipment != null) ? equipment.Replace(slot, item) : item;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f4672396b9b81a2438d5321c4a24541b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,197 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Abstract UI component observing an item somewhere in the inventory. This item can be equipped on
/// the character, it can be lying in a chest, or it can be hot-linked by another player. Either way,
/// all the common behavior is in this class. What the observed item actually is...
/// that's up to the derived class to determine.
/// </summary>
public abstract class UIItemSlot : MonoBehaviour
{
public UISprite icon;
public UIWidget background;
public UILabel label;
public AudioClip grabSound;
public AudioClip placeSound;
public AudioClip errorSound;
InvGameItem mItem;
string mText = "";
static InvGameItem mDraggedItem;
/// <summary>
/// This function should return the item observed by this UI class.
/// </summary>
abstract protected InvGameItem observedItem { get; }
/// <summary>
/// Replace the observed item with the specified value. Should return the item that was replaced.
/// </summary>
abstract protected InvGameItem Replace (InvGameItem item);
/// <summary>
/// Show a tooltip for the item.
/// </summary>
void OnTooltip (bool show)
{
InvGameItem item = show ? mItem : null;
if (item != null)
{
InvBaseItem bi = item.baseItem;
if (bi != null)
{
string t = "[" + NGUIText.EncodeColor(item.color) + "]" + item.name + "[-]\n";
t += "[AFAFAF]Level " + item.itemLevel + " " + bi.slot;
List<InvStat> stats = item.CalculateStats();
for (int i = 0, imax = stats.Count; i < imax; ++i)
{
InvStat stat = stats[i];
if (stat.amount == 0) continue;
if (stat.amount < 0)
{
t += "\n[FF0000]" + stat.amount;
}
else
{
t += "\n[00FF00]+" + stat.amount;
}
if (stat.modifier == InvStat.Modifier.Percent) t += "%";
t += " " + stat.id;
t += "[-]";
}
if (!string.IsNullOrEmpty(bi.description)) t += "\n[FF9900]" + bi.description;
UITooltip.Show(t);
return;
}
}
UITooltip.Hide();
}
/// <summary>
/// Allow to move objects around via drag & drop.
/// </summary>
void OnClick ()
{
if (mDraggedItem != null)
{
OnDrop(null);
}
else if (mItem != null)
{
mDraggedItem = Replace(null);
if (mDraggedItem != null) NGUITools.PlaySound(grabSound);
UpdateCursor();
}
}
/// <summary>
/// Start dragging the item.
/// </summary>
void OnDrag (Vector2 delta)
{
if (mDraggedItem == null && mItem != null)
{
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
mDraggedItem = Replace(null);
NGUITools.PlaySound(grabSound);
UpdateCursor();
}
}
/// <summary>
/// Stop dragging the item.
/// </summary>
void OnDrop (GameObject go)
{
InvGameItem item = Replace(mDraggedItem);
if (mDraggedItem == item) NGUITools.PlaySound(errorSound);
else if (item != null) NGUITools.PlaySound(grabSound);
else NGUITools.PlaySound(placeSound);
mDraggedItem = item;
UpdateCursor();
}
/// <summary>
/// Set the cursor to the icon of the item being dragged.
/// </summary>
void UpdateCursor ()
{
if (mDraggedItem != null && mDraggedItem.baseItem != null)
{
UICursor.Set(mDraggedItem.baseItem.iconAtlas, mDraggedItem.baseItem.iconName);
}
else
{
UICursor.Clear();
}
}
/// <summary>
/// Keep an eye on the item and update the icon when it changes.
/// </summary>
void Update ()
{
InvGameItem i = observedItem;
if (mItem != i)
{
mItem = i;
InvBaseItem baseItem = (i != null) ? i.baseItem : null;
if (label != null)
{
string itemName = (i != null) ? i.name : null;
if (string.IsNullOrEmpty(mText)) mText = label.text;
label.text = (itemName != null) ? itemName : mText;
}
if (icon != null)
{
if (baseItem == null || baseItem.iconAtlas == null)
{
icon.enabled = false;
}
else
{
icon.atlas = baseItem.iconAtlas;
icon.spriteName = baseItem.iconName;
icon.enabled = true;
icon.MakePixelPerfect();
}
}
if (background != null)
{
background.color = (i != null) ? i.color : Color.white;
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ef0e623fb2aaa4f4fbf65633917519a5
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,130 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Storage container that stores items.
/// </summary>
[AddComponentMenu("NGUI/Examples/UI Item Storage")]
public class UIItemStorage : MonoBehaviour
{
/// <summary>
/// Maximum size of the container. Adding more items than this number will not work.
/// </summary>
public int maxItemCount = 8;
/// <summary>
/// Maximum number of rows to create.
/// </summary>
public int maxRows = 4;
/// <summary>
/// Maximum number of columns to create.
/// </summary>
public int maxColumns = 4;
/// <summary>
/// Template used to create inventory icons.
/// </summary>
public GameObject template;
/// <summary>
/// Background widget to scale after the item slots have been created.
/// </summary>
public UIWidget background;
/// <summary>
/// Spacing between icons.
/// </summary>
public int spacing = 128;
/// <summary>
/// Padding around the border.
/// </summary>
public int padding = 10;
List<InvGameItem> mItems = new List<InvGameItem>();
/// <summary>
/// List of items in the container.
/// </summary>
public List<InvGameItem> items { get { while (mItems.Count < maxItemCount) mItems.Add(null); return mItems; } }
/// <summary>
/// Convenience function that returns an item at the specified slot.
/// </summary>
public InvGameItem GetItem (int slot) { return (slot < items.Count) ? mItems[slot] : null; }
/// <summary>
/// Replace an item in the container with the specified one.
/// </summary>
/// <returns>An item that was replaced.</returns>
public InvGameItem Replace (int slot, InvGameItem item)
{
if (slot < maxItemCount)
{
InvGameItem prev = items[slot];
mItems[slot] = item;
return prev;
}
return item;
}
/// <summary>
/// Initialize the container and create an appropriate number of UI slots.
/// </summary>
void Start ()
{
if (template != null)
{
int count = 0;
Bounds b = new Bounds();
for (int y = 0; y < maxRows; ++y)
{
for (int x = 0; x < maxColumns; ++x)
{
GameObject go = NGUITools.AddChild(gameObject, template);
Transform t = go.transform;
t.localPosition = new Vector3(padding + (x + 0.5f) * spacing, -padding - (y + 0.5f) * spacing, 0f);
UIStorageSlot slot = go.GetComponent<UIStorageSlot>();
if (slot != null)
{
slot.storage = this;
slot.slot = count;
}
b.Encapsulate(new Vector3(padding * 2f + (x + 1) * spacing, -padding * 2f - (y + 1) * spacing, 0f));
if (++count >= maxItemCount)
{
if (background != null)
{
background.transform.localScale = b.size;
}
return;
}
}
}
if (background != null) background.transform.localScale = b.size;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 849fd93d348255049af49ba16fb8bcb0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,34 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// A UI script that keeps an eye on the slot in a storage container.
/// </summary>
[AddComponentMenu("NGUI/Examples/UI Storage Slot")]
public class UIStorageSlot : UIItemSlot
{
public UIItemStorage storage;
public int slot = 0;
override protected InvGameItem observedItem
{
get
{
return (storage != null) ? storage.GetItem(slot) : null;
}
}
/// <summary>
/// Replace the observed item with the specified value. Should return the item that was replaced.
/// </summary>
override protected InvGameItem Replace (InvGameItem item)
{
return (storage != null) ? storage.Replace(slot, item) : item;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 70841457d1e5b744593d9ffe219188ae
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: cf9f82e9121954e4ab411f5c174b53ce
folderAsset: yes
timeCreated: 1516240530
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Item Attachment Point")]
public class InvAttachmentPoint : MonoBehaviour
{
/// <summary>
/// Item slot that this attachment point covers.
/// </summary>
public InvBaseItem.Slot slot;
GameObject mPrefab;
GameObject mChild;
/// <summary>
/// Attach an instance of the specified game object.
/// </summary>
public GameObject Attach (GameObject prefab)
{
if (mPrefab != prefab)
{
mPrefab = prefab;
// Remove the previous child
if (mChild != null) Destroy(mChild);
// If we have something to create, let's do so now
if (mPrefab != null)
{
// Create a new instance of the game object
Transform t = transform;
mChild = Instantiate(mPrefab, t.position, t.rotation) as GameObject;
// Parent the child to this object
Transform ct = mChild.transform;
ct.parent = t;
// Reset the pos/rot/scale, just in case
ct.localPosition = Vector3.zero;
ct.localRotation = Quaternion.identity;
ct.localScale = Vector3.one;
}
}
return mChild;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2a05a718b5cd2ae4eb90743bca9a1032
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,92 @@
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Inventory System -- Base Item. Note that it would be incredibly tedious to create all items by hand, Warcraft style.
/// It's a lot more straightforward to create all items to be of the same level as far as stats go, then specify an
/// appropriate level range for the item where it will appear. Effective item stats can then be calculated by lowering
/// the base stats by an appropriate amount. Add a quality modifier, and you have additional variety, Terraria 1.1 style.
/// </summary>
[System.Serializable]
public class InvBaseItem
{
public enum Slot
{
None, // First element MUST be 'None'
Weapon, // All the following elements are yours to customize -- edit, add or remove as you desire
Shield,
Body,
Shoulders,
Bracers,
Boots,
Trinket,
_LastDoNotUse, // Flash export doesn't support Enum.GetNames :(
}
/// <summary>
/// 16-bit item ID, generated by the system.
/// Not to be confused with a 32-bit item ID, which actually contains the ID of the database as its prefix.
/// </summary>
public int id16;
/// <summary>
/// Name of this item.
/// </summary>
public string name;
/// <summary>
/// This item's custom description.
/// </summary>
public string description;
/// <summary>
/// Slot that this item belongs to.
/// </summary>
public Slot slot = Slot.None;
/// <summary>
/// Minimum and maximum allowed level for this item. When random loot gets generated,
/// only items within appropriate level should be considered.
/// </summary>
public int minItemLevel = 1;
public int maxItemLevel = 50;
/// <summary>
/// And and all base stats this item may have at a maximum level (50).
/// Actual object's stats are calculated based on item's level and quality.
/// </summary>
public List<InvStat> stats = new List<InvStat>();
/// <summary>
/// Game Object that will be created and attached to the specified slot on the body.
/// This should typically be a prefab with a renderer component, such as a sword,
/// a bracer, shield, etc.
/// </summary>
public GameObject attachment;
/// <summary>
/// Object's main material color.
/// </summary>
public Color color = Color.white;
/// <summary>
/// Atlas used for the item's icon.
/// </summary>
public UIAtlas iconAtlas;
/// <summary>
/// Name of the icon's sprite within the atlas.
/// </summary>
public string iconName = "";
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ed0e631b209a1b2429fe081e9717671b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,139 @@
using UnityEngine;
using System.Collections.Generic;
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Examples/Item Database")]
public class InvDatabase : MonoBehaviour
{
// Cached list of all available item databases
static InvDatabase[] mList;
static bool mIsDirty = true;
/// <summary>
/// Retrieves the list of item databases, finding all instances if necessary.
/// </summary>
static public InvDatabase[] list
{
get
{
if (mIsDirty)
{
mIsDirty = false;
mList = NGUITools.FindActive<InvDatabase>();
}
return mList;
}
}
/// <summary>
/// Each database should have a unique 16-bit ID. When the items are saved, database IDs
/// get combined with item IDs to create 32-bit IDs containing both values.
/// </summary>
public int databaseID = 0;
/// <summary>
/// List of items in this database.
/// </summary>
public List<InvBaseItem> items = new List<InvBaseItem>();
/// <summary>
/// UI atlas used for icons.
/// </summary>
public UIAtlas iconAtlas;
/// <summary>
/// Add this database to the list.
/// </summary>
void OnEnable () { mIsDirty = true; }
/// <summary>
/// Remove this database from the list.
/// </summary>
void OnDisable () { mIsDirty = true; }
/// <summary>
/// Find an item by its 16-bit ID.
/// </summary>
InvBaseItem GetItem (int id16)
{
for (int i = 0, imax = items.Count; i < imax; ++i)
{
InvBaseItem item = items[i];
if (item.id16 == id16) return item;
}
return null;
}
/// <summary>
/// Find a database given its ID.
/// </summary>
static InvDatabase GetDatabase (int dbID)
{
for (int i = 0, imax = list.Length; i < imax; ++i)
{
InvDatabase db = list[i];
if (db.databaseID == dbID) return db;
}
return null;
}
/// <summary>
/// Find the specified item given its full 32-bit ID (not to be confused with individual 16-bit item IDs).
/// </summary>
static public InvBaseItem FindByID (int id32)
{
InvDatabase db = GetDatabase(id32 >> 16);
return (db != null) ? db.GetItem(id32 & 0xFFFF) : null;
}
/// <summary>
/// Find the item with the specified name.
/// </summary>
static public InvBaseItem FindByName (string exact)
{
for (int i = 0, imax = list.Length; i < imax; ++i)
{
InvDatabase db = list[i];
for (int b = 0, bmax = db.items.Count; b < bmax; ++b)
{
InvBaseItem item = db.items[b];
if (item.name == exact)
{
return item;
}
}
}
return null;
}
/// <summary>
/// Get the full 32-bit ID of the specified item.
/// Use this to get a list of items on the character that can get saved out to an external database or file.
/// </summary>
static public int FindItemID (InvBaseItem item)
{
for (int i = 0, imax = list.Length; i < imax; ++i)
{
InvDatabase db = list[i];
if (db.items.Contains(item))
{
return (db.databaseID << 16) | item.id16;
}
}
return -1;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5be182ce83f3ee04b941134953597507
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,157 @@
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Inventory system -- Equipment class works with InvAttachmentPoints and allows to visually equip and remove items.
/// </summary>
[AddComponentMenu("NGUI/Examples/Equipment")]
public class InvEquipment : MonoBehaviour
{
InvGameItem[] mItems;
InvAttachmentPoint[] mAttachments;
/// <summary>
/// List of equipped items (with a finite number of equipment slots).
/// </summary>
public InvGameItem[] equippedItems { get { return mItems; } }
/// <summary>
/// Equip the specified item automatically replacing an existing one.
/// </summary>
public InvGameItem Replace (InvBaseItem.Slot slot, InvGameItem item)
{
InvBaseItem baseItem = (item != null) ? item.baseItem : null;
if (slot != InvBaseItem.Slot.None)
{
// If the item is not of appropriate type, we shouldn't do anything
if (baseItem != null && baseItem.slot != slot) return item;
if (mItems == null)
{
// Automatically figure out how many item slots we need
int count = (int)InvBaseItem.Slot._LastDoNotUse;
mItems = new InvGameItem[count];
}
// Equip this item
InvGameItem prev = mItems[(int)slot - 1];
mItems[(int)slot - 1] = item;
// Get the list of all attachment points
if (mAttachments == null) mAttachments = GetComponentsInChildren<InvAttachmentPoint>();
// Equip the item visually
for (int i = 0, imax = mAttachments.Length; i < imax; ++i)
{
InvAttachmentPoint ip = mAttachments[i];
if (ip.slot == slot)
{
GameObject go = ip.Attach(baseItem != null ? baseItem.attachment : null);
if (baseItem != null && go != null)
{
Renderer ren = go.GetComponent<Renderer>();
if (ren != null) ren.material.color = baseItem.color;
}
}
}
return prev;
}
else if (item != null)
{
Debug.LogWarning("Can't equip \"" + item.name + "\" because it doesn't specify an item slot");
}
return item;
}
/// <summary>
/// Equip the specified item and return the item that was replaced.
/// </summary>
public InvGameItem Equip (InvGameItem item)
{
if (item != null)
{
InvBaseItem baseItem = item.baseItem;
if (baseItem != null) return Replace(baseItem.slot, item);
else Debug.LogWarning("Can't resolve the item ID of " + item.baseItemID);
}
return item;
}
/// <summary>
/// Unequip the specified item, returning it if the operation was successful.
/// </summary>
public InvGameItem Unequip (InvGameItem item)
{
if (item != null)
{
InvBaseItem baseItem = item.baseItem;
if (baseItem != null) return Replace(baseItem.slot, null);
}
return item;
}
/// <summary>
/// Unequip the item from the specified slot, returning the item that was unequipped.
/// </summary>
public InvGameItem Unequip (InvBaseItem.Slot slot) { return Replace(slot, null); }
/// <summary>
/// Whether the specified item is currently equipped.
/// </summary>
public bool HasEquipped (InvGameItem item)
{
if (mItems != null)
{
for (int i = 0, imax = mItems.Length; i < imax; ++i)
{
if (mItems[i] == item) return true;
}
}
return false;
}
/// <summary>
/// Whether the specified slot currently has an item equipped.
/// </summary>
public bool HasEquipped (InvBaseItem.Slot slot)
{
if (mItems != null)
{
for (int i = 0, imax = mItems.Length; i < imax; ++i)
{
InvBaseItem baseItem = mItems[i].baseItem;
if (baseItem != null && baseItem.slot == slot) return true;
}
}
return false;
}
/// <summary>
/// Retrieves the item in the specified slot.
/// </summary>
public InvGameItem GetItem (InvBaseItem.Slot slot)
{
if (slot != InvBaseItem.Slot.None)
{
int index = (int)slot - 1;
if (mItems != null && index < mItems.Length)
{
return mItems[index];
}
}
return null;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 669bf9dcd99e8c6448f446db4f3c10fc
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,212 @@
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Since it would be incredibly tedious to create thousands of unique items by hand, a simple solution is needed.
/// Separating items into 2 parts is that solution. Base item contains stats that the item would have if it was max
/// level. All base items are created with their stats at max level. Game item, the second item class, has an
/// effective item level which is used to calculate effective item stats. Game items can be generated with a random
/// level (clamped within base item's min/max level range), and with random quality affecting the item's stats.
/// </summary>
[System.Serializable]
public class InvGameItem
{
public enum Quality
{
Broken,
Cursed,
Damaged,
Worn,
Sturdy, // Normal quality
Polished,
Improved,
Crafted,
Superior,
Enchanted,
Epic,
Legendary,
_LastDoNotUse, // Flash export doesn't support Enum.GetNames :(
}
// ID of the base item used to create this game item
[SerializeField] int mBaseItemID = 0;
/// <summary>
/// Item quality -- applies a penalty or bonus to all base stats.
/// </summary>
public Quality quality = Quality.Sturdy;
/// <summary>
/// Item's effective level.
/// </summary>
public int itemLevel = 1;
// Cached for speed
InvBaseItem mBaseItem;
/// <summary>
/// ID of the base item used to create this one.
/// </summary>
public int baseItemID { get { return mBaseItemID; } }
/// <summary>
/// Base item used by this game item.
/// </summary>
public InvBaseItem baseItem
{
get
{
if (mBaseItem == null)
{
mBaseItem = InvDatabase.FindByID(baseItemID);
}
return mBaseItem;
}
}
/// <summary>
/// Game item's name should prefix the quality
/// </summary>
public string name
{
get
{
if (baseItem == null) return null;
return quality.ToString() + " " + baseItem.name;
}
}
/// <summary>
/// Put your formula for calculating the item stat modifier here.
/// Simplest formula -- scale it with quality and item level.
/// Since all stats on base items are specified at max item level,
/// calculating the effective multiplier is as simple as itemLevel/maxLevel.
/// </summary>
public float statMultiplier
{
get
{
float mult = 0f;
switch (quality)
{
case Quality.Cursed: mult = -1f; break;
case Quality.Broken: mult = 0f; break;
case Quality.Damaged: mult = 0.25f; break;
case Quality.Worn: mult = 0.9f; break;
case Quality.Sturdy: mult = 1f; break;
case Quality.Polished: mult = 1.1f; break;
case Quality.Improved: mult = 1.25f; break;
case Quality.Crafted: mult = 1.5f; break;
case Quality.Superior: mult = 1.75f; break;
case Quality.Enchanted: mult = 2f; break;
case Quality.Epic: mult = 2.5f; break;
case Quality.Legendary: mult = 3f; break;
}
// Take item's level into account
float linear = itemLevel / 50f;
// Add a curve for more interesting results
mult *= Mathf.Lerp(linear, linear * linear, 0.5f);
return mult;
}
}
/// <summary>
/// Item's color based on quality. You will likely want to change this to your own colors.
/// </summary>
public Color color
{
get
{
Color c = Color.white;
switch (quality)
{
case Quality.Cursed: c = Color.red; break;
case Quality.Broken: c = new Color(0.4f, 0.2f, 0.2f); break;
case Quality.Damaged: c = new Color(0.4f, 0.4f, 0.4f); break;
case Quality.Worn: c = new Color(0.7f, 0.7f, 0.7f); break;
case Quality.Sturdy: c = new Color(1.0f, 1.0f, 1.0f); break;
case Quality.Polished: c = NGUIMath.HexToColor(0xe0ffbeff); break;
case Quality.Improved: c = NGUIMath.HexToColor(0x93d749ff); break;
case Quality.Crafted: c = NGUIMath.HexToColor(0x4eff00ff); break;
case Quality.Superior: c = NGUIMath.HexToColor(0x00baffff); break;
case Quality.Enchanted: c = NGUIMath.HexToColor(0x7376fdff); break;
case Quality.Epic: c = NGUIMath.HexToColor(0x9600ffff); break;
case Quality.Legendary: c = NGUIMath.HexToColor(0xff9000ff); break;
}
return c;
}
}
/// <summary>
/// Create a game item with the specified ID.
/// </summary>
public InvGameItem (int id) { mBaseItemID = id; }
/// <summary>
/// Create a game item with the specified ID and base item.
/// </summary>
public InvGameItem (int id, InvBaseItem bi) { mBaseItemID = id; mBaseItem = bi; }
/// <summary>
/// Calculate and return the list of effective stats based on item level and quality.
/// </summary>
public List<InvStat> CalculateStats ()
{
List<InvStat> stats = new List<InvStat>();
if (baseItem != null)
{
float mult = statMultiplier;
List<InvStat> baseStats = baseItem.stats;
for (int i = 0, imax = baseStats.Count; i < imax; ++i)
{
InvStat bs = baseStats[i];
int amount = Mathf.RoundToInt(mult * bs.amount);
if (amount == 0) continue;
bool found = false;
for (int b = 0, bmax = stats.Count; b < bmax; ++b)
{
InvStat s = stats[b];
if (s.id == bs.id && s.modifier == bs.modifier)
{
s.amount += amount;
found = true;
break;
}
}
if (!found)
{
InvStat stat = new InvStat();
stat.id = bs.id;
stat.amount = amount;
stat.modifier = bs.modifier;
stats.Add(stat);
}
}
// This would be the place to determine if it's a weapon or armor and sort stats accordingly
stats.Sort(InvStat.CompareArmor);
}
return stats;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 94ca21840c42aad40b9f5229b16282d4
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,123 @@
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Inventory System statistic
/// </summary>
[System.Serializable]
public class InvStat
{
/// <summary>
/// Customize this enum with statistics appropriate for your own game
/// </summary>
public enum Identifier
{
Strength,
Constitution,
Agility,
Intelligence,
Damage,
Crit,
Armor,
Health,
Mana,
Other,
}
/// <summary>
/// Formula for final stats: [sum of raw amounts] * (1 + [sum of percent amounts])
/// </summary>
public enum Modifier
{
Added,
Percent,
}
public Identifier id;
public Modifier modifier;
public int amount;
/// <summary>
/// Get the localized name of the stat.
/// </summary>
static public string GetName (Identifier i)
{
return i.ToString();
}
/// <summary>
/// Get the localized stat's description -- adjust this to fit your own stats.
/// </summary>
static public string GetDescription (Identifier i)
{
switch (i)
{
case Identifier.Strength: return "Strength increases melee damage";
case Identifier.Constitution: return "Constitution increases health";
case Identifier.Agility: return "Agility increases armor";
case Identifier.Intelligence: return "Intelligence increases mana";
case Identifier.Damage: return "Damage adds to the amount of damage done in combat";
case Identifier.Crit: return "Crit increases the chance of landing a critical strike";
case Identifier.Armor: return "Armor protects from damage";
case Identifier.Health: return "Health prolongs life";
case Identifier.Mana: return "Mana increases the number of spells that can be cast";
}
return null;
}
/// <summary>
/// Comparison function for sorting armor. Armor value will show up first, followed by damage.
/// </summary>
static public int CompareArmor (InvStat a, InvStat b)
{
int ia = (int)a.id;
int ib = (int)b.id;
if (a.id == Identifier.Armor) ia -= 10000;
else if (a.id == Identifier.Damage) ia -= 5000;
if (b.id == Identifier.Armor) ib -= 10000;
else if (b.id == Identifier.Damage) ib -= 5000;
if (a.amount < 0) ia += 1000;
if (b.amount < 0) ib += 1000;
if (a.modifier == Modifier.Percent) ia += 100;
if (b.modifier == Modifier.Percent) ib += 100;
// Not using ia.CompareTo(ib) here because Flash export doesn't understand that
if (ia < ib) return -1;
if (ia > ib) return 1;
return 0;
}
/// <summary>
/// Comparison function for sorting weapons. Damage value will show up first, followed by armor.
/// </summary>
static public int CompareWeapon (InvStat a, InvStat b)
{
int ia = (int)a.id;
int ib = (int)b.id;
if (a.id == Identifier.Damage) ia -= 10000;
else if (a.id == Identifier.Armor) ia -= 5000;
if (b.id == Identifier.Damage) ib -= 10000;
else if (b.id == Identifier.Armor) ib -= 5000;
if (a.amount < 0) ia += 1000;
if (b.amount < 0) ib += 1000;
if (a.modifier == Modifier.Percent) ia += 100;
if (b.modifier == Modifier.Percent) ib += 100;
if (ia < ib) return -1;
if (ia > ib) return 1;
return 0;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 82b955af6f248024a8bf6a788bedb6fd
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4b5844c4c66f34d45acb150ff8077ebd
folderAsset: yes
timeCreated: 1516240530
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,54 @@
using UnityEngine;
/// <summary>
/// Very simple example of how to use a TextList with a UIInput for chat.
/// </summary>
[RequireComponent(typeof(UIInput))]
[AddComponentMenu("NGUI/Examples/Chat Input")]
public class ChatInput : MonoBehaviour
{
public UITextList textList;
public bool fillWithDummyData = false;
UIInput mInput;
/// <summary>
/// Add some dummy text to the text list.
/// </summary>
void Start ()
{
mInput = GetComponent<UIInput>();
mInput.label.maxLineCount = 1;
if (fillWithDummyData && textList != null)
{
for (int i = 0; i < 30; ++i)
{
textList.Add(((i % 2 == 0) ? "[FFFFFF]" : "[AAAAAA]") +
"This is an example paragraph for the text list, testing line " + i + "[-]");
}
}
}
/// <summary>
/// Submit notification is sent by UIInput when 'enter' is pressed or iOS/Android keyboard finalizes input.
/// </summary>
public void OnSubmit ()
{
if (textList != null)
{
// It's a good idea to strip out all symbols as we don't want user input to alter colors, add new lines, etc
string text = NGUIText.StripSymbols(mInput.value);
if (!string.IsNullOrEmpty(text))
{
textList.Add(text);
mInput.value = "";
mInput.isSelected = false;
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0c4f0ea813e2aef4588e27970990027a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,40 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections;
/// <summary>
/// Simple script that shows how to download a remote texture and assign it to be used by a UITexture.
/// </summary>
[RequireComponent(typeof(UITexture))]
public class DownloadTexture : MonoBehaviour
{
public string url = "http://www.yourwebsite.com/logo.png";
public bool pixelPerfect = true;
Texture2D mTex;
IEnumerator Start ()
{
WWW www = new WWW(url);
yield return www;
mTex = www.texture;
if (mTex != null)
{
UITexture ut = GetComponent<UITexture>();
ut.mainTexture = mTex;
if (pixelPerfect) ut.MakePixelPerfect();
}
www.Dispose();
}
void OnDestroy ()
{
if (mTex != null) Destroy(mTex);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 28e7f0f53a61c6842a620d1114ae614f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,56 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Example script that resizes the widget it's attached to in order to envelop the target content.
/// </summary>
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/Examples/Envelop Content")]
public class EnvelopContent : MonoBehaviour
{
public Transform targetRoot;
public int padLeft = 0;
public int padRight = 0;
public int padBottom = 0;
public int padTop = 0;
bool mStarted = false;
void Start ()
{
mStarted = true;
Execute();
}
void OnEnable () { if (mStarted) Execute(); }
[ContextMenu("Execute")]
public void Execute ()
{
if (targetRoot == transform)
{
Debug.LogError("Target Root object cannot be the same object that has Envelop Content. Make it a sibling instead.", this);
}
else if (NGUITools.IsChild(targetRoot, transform))
{
Debug.LogError("Target Root object should not be a parent of Envelop Content. Make it a sibling instead.", this);
}
else
{
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(transform.parent, targetRoot, false);
float x0 = b.min.x + padLeft;
float y0 = b.min.y + padBottom;
float x1 = b.max.x + padRight;
float y1 = b.max.y + padTop;
UIWidget w = GetComponent<UIWidget>();
w.SetRect(x0, y0, x1 - x0, y1 - y0);
BroadcastMessage("UpdateAnchors", SendMessageOptions.DontRequireReceiver);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: afc132d2169cbe0478182768b713d882
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,47 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Drag and Drop Item (Example)")]
public class ExampleDragDropItem : UIDragDropItem
{
/// <summary>
/// Prefab object that will be instantiated on the DragDropSurface if it receives the OnDrop event.
/// </summary>
public GameObject prefab;
/// <summary>
/// Drop a 3D game object onto the surface.
/// </summary>
protected override void OnDragDropRelease (GameObject surface)
{
if (surface != null)
{
ExampleDragDropSurface dds = surface.GetComponent<ExampleDragDropSurface>();
if (dds != null)
{
GameObject child = NGUITools.AddChild(dds.gameObject, prefab);
child.transform.localScale = dds.transform.localScale;
Transform trans = child.transform;
// trans.position = UICamera.lastWorldPosition;
if (dds.rotatePlacedObject)
{
trans.rotation = Quaternion.LookRotation(UICamera.lastHit.normal) * Quaternion.Euler(90f, 0f, 0f);
}
// Destroy this icon as it's no longer needed
NGUITools.Destroy(gameObject);
return;
}
}
base.OnDragDropRelease(surface);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d331b94ba7bbfa343bb6b9f9282b5c93
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,32 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example of an OnDrop event accepting a game object. In this case we check to see if there is a DragDropObject present,
/// and if so -- create its prefab on the surface, then destroy the object.
/// </summary>
[AddComponentMenu("NGUI/Examples/Drag and Drop Surface (Example)")]
public class ExampleDragDropSurface : MonoBehaviour
{
public bool rotatePlacedObject = false;
//void OnDrop (GameObject go)
//{
// ExampleDragDropItem ddo = go.GetComponent<ExampleDragDropItem>();
// if (ddo != null)
// {
// GameObject child = NGUITools.AddChild(gameObject, ddo.prefab);
// Transform trans = child.transform;
// trans.position = UICamera.lastWorldPosition;
// if (rotatePlacedObject) trans.rotation = Quaternion.LookRotation(UICamera.lastHit.normal) * Quaternion.Euler(90f, 0f, 0f);
// Destroy(go);
// }
//}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5c645c85ed4826348b5000ddccd0f936
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,50 @@
using UnityEngine;
/// <summary>
/// Attach to a game object to make its position always lag behind its parent as the parent moves.
/// </summary>
public class LagPosition : MonoBehaviour
{
public Vector3 speed = new Vector3(10f, 10f, 10f);
public bool ignoreTimeScale = false;
Transform mTrans;
Vector3 mRelative;
Vector3 mAbsolute;
bool mStarted = false;
public void OnRepositionEnd ()
{
Interpolate(1000f);
}
void Interpolate (float delta)
{
Transform parent = mTrans.parent;
if (parent != null)
{
Vector3 target = parent.position + parent.rotation * mRelative;
mAbsolute.x = Mathf.Lerp(mAbsolute.x, target.x, Mathf.Clamp01(delta * speed.x));
mAbsolute.y = Mathf.Lerp(mAbsolute.y, target.y, Mathf.Clamp01(delta * speed.y));
mAbsolute.z = Mathf.Lerp(mAbsolute.z, target.z, Mathf.Clamp01(delta * speed.z));
mTrans.position = mAbsolute;
}
}
void Awake () { mTrans = transform; }
void OnEnable () { if (mStarted) ResetPosition(); }
void Start () { mStarted = true; ResetPosition(); }
public void ResetPosition ()
{
mAbsolute = mTrans.position;
mRelative = mTrans.localPosition;
}
void Update ()
{
Interpolate(ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7e58031db5aeb444da199e06c340c871
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 51
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,47 @@
using UnityEngine;
/// <summary>
/// Attach to a game object to make its rotation always lag behind its parent as the parent rotates.
/// </summary>
[AddComponentMenu("NGUI/Examples/Lag Rotation")]
public class LagRotation : MonoBehaviour
{
public float speed = 10f;
public bool ignoreTimeScale = false;
Transform mTrans;
Quaternion mRelative;
Quaternion mAbsolute;
public void OnRepositionEnd ()
{
Interpolate(1000f);
}
void Interpolate (float delta)
{
if (mTrans != null)
{
Transform parent = mTrans.parent;
if (parent != null)
{
mAbsolute = Quaternion.Slerp(mAbsolute, parent.rotation * mRelative, delta * speed);
mTrans.rotation = mAbsolute;
}
}
}
void Start ()
{
mTrans = transform;
mRelative = mTrans.localRotation;
mAbsolute = mTrans.rotation;
}
void Update ()
{
Interpolate(ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b2f7cad6a754193478a36b8177641278
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 52
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,15 @@
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Load Level On Click")]
public class LoadLevelOnClick : MonoBehaviour
{
public string levelName;
void OnClick ()
{
if (!string.IsNullOrEmpty(levelName))
{
Application.LoadLevel(levelName);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4df31385379812441bfc75a419c76729
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,36 @@
using UnityEngine;
/// <summary>
/// Attaching this script to an object will make that object face the specified target.
/// The most ideal use for this script is to attach it to the camera and make the camera look at its target.
/// </summary>
[AddComponentMenu("NGUI/Examples/Look At Target")]
public class LookAtTarget : MonoBehaviour
{
public int level = 0;
public Transform target;
public float speed = 8f;
Transform mTrans;
void Start ()
{
mTrans = transform;
}
void LateUpdate ()
{
if (target != null)
{
Vector3 dir = target.position - mTrans.position;
float mag = dir.magnitude;
if (mag > 0.001f)
{
Quaternion lookRot = Quaternion.LookRotation(dir);
mTrans.rotation = Quaternion.Slerp(mTrans.rotation, lookRot, Mathf.Clamp01(speed * Time.deltaTime));
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2beca3ab63dabae4782a28898bed8b06
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,15 @@
using UnityEngine;
public class OpenURLOnClick : MonoBehaviour
{
void OnClick ()
{
UILabel lbl = GetComponent<UILabel>();
if (lbl != null)
{
string url = lbl.GetUrlAtPosition(UICamera.lastWorldPosition);
if (!string.IsNullOrEmpty(url)) Application.OpenURL(url);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7f4e76ca1e5bd9d41938bc027a0aa6b9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,37 @@
using UnityEngine;
/// <summary>
/// Placing this script on the game object will make that game object pan with mouse movement.
/// </summary>
[AddComponentMenu("NGUI/Examples/Pan With Mouse")]
public class PanWithMouse : MonoBehaviour
{
public Vector2 degrees = new Vector2(5f, 3f);
public float range = 1f;
Transform mTrans;
Quaternion mStart;
Vector2 mRot = Vector2.zero;
void Start ()
{
mTrans = transform;
mStart = mTrans.localRotation;
}
void Update ()
{
float delta = RealTime.deltaTime;
Vector3 pos = Input.mousePosition;
float halfWidth = Screen.width * 0.5f;
float halfHeight = Screen.height * 0.5f;
if (range < 0.1f) range = 0.1f;
float x = Mathf.Clamp((pos.x - halfWidth) / halfWidth / range, -1f, 1f);
float y = Mathf.Clamp((pos.y - halfHeight) / halfHeight / range, -1f, 1f);
mRot = Vector2.Lerp(mRot, new Vector2(x, y), delta * 5f);
mTrans.localRotation = mStart * Quaternion.Euler(-mRot.y * degrees.y, mRot.x * degrees.x, 0f);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cef9873bc3783e249b519e15ee14b35a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,88 @@
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Attach this script to any object that has idle animations.
/// It's expected that the main idle loop animation is called "idle", and idle
/// break animations all begin with "idle" (ex: idleStretch, idleYawn, etc).
/// The script will place the idle loop animation on layer 0, and breaks on layer 1.
/// </summary>
[AddComponentMenu("NGUI/Examples/Play Idle Animations")]
public class PlayIdleAnimations : MonoBehaviour
{
Animation mAnim;
AnimationClip mIdle;
List<AnimationClip> mBreaks = new List<AnimationClip>();
float mNextBreak = 0f;
int mLastIndex = 0;
/// <summary>
/// Find all idle animations.
/// </summary>
void Start ()
{
mAnim = GetComponentInChildren<Animation>();
if (mAnim == null)
{
Debug.LogWarning(NGUITools.GetHierarchy(gameObject) + " has no Animation component");
Destroy(this);
}
else
{
foreach (AnimationState state in mAnim)
{
if (state.clip.name == "idle")
{
state.layer = 0;
mIdle = state.clip;
mAnim.Play(mIdle.name);
}
else if (state.clip.name.StartsWith("idle"))
{
state.layer = 1;
mBreaks.Add(state.clip);
}
}
// No idle breaks found -- this script is unnecessary
if (mBreaks.Count == 0) Destroy(this);
}
}
/// <summary>
/// If it's time to play a new idle break animation, do so.
/// </summary>
void Update ()
{
if (mNextBreak < Time.time)
{
if (mBreaks.Count == 1)
{
// Only one break animation
AnimationClip clip = mBreaks[0];
mNextBreak = Time.time + clip.length + Random.Range(5f, 15f);
mAnim.CrossFade(clip.name);
}
else
{
int index = Random.Range(0, mBreaks.Count - 1);
// Never choose the same animation twice in a row
if (mLastIndex == index)
{
++index;
if (index >= mBreaks.Count) index = 0;
}
mLastIndex = index;
AnimationClip clip = mBreaks[index];
mNextBreak = Time.time + clip.length + Random.Range(2f, 8f);
mAnim.CrossFade(clip.name);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e7393c14f99274841887c9890b46216d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,30 @@
using UnityEngine;
/// <summary>
/// Simple script used by Tutorial 11 that sets the color of the sprite based on the string value.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/Examples/Set Color on Selection")]
public class SetColorOnSelection : MonoBehaviour
{
UIWidget mWidget;
public void SetSpriteBySelection ()
{
if (UIPopupList.current == null) return;
if (mWidget == null) mWidget = GetComponent<UIWidget>();
switch (UIPopupList.current.value)
{
case "White": mWidget.color = Color.white; break;
case "Red": mWidget.color = Color.red; break;
case "Green": mWidget.color = Color.green; break;
case "Blue": mWidget.color = Color.blue; break;
case "Yellow": mWidget.color = Color.yellow; break;
case "Cyan": mWidget.color = Color.cyan; break;
case "Magenta": mWidget.color = Color.magenta; break;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1c0c14d2698771846ad203a553cbc444
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,52 @@
using UnityEngine;
/// <summary>
/// Want something to spin? Attach this script to it. Works equally well with rigidbodies as without.
/// </summary>
[AddComponentMenu("NGUI/Examples/Spin")]
public class Spin : MonoBehaviour
{
public Vector3 rotationsPerSecond = new Vector3(0f, 0.1f, 0f);
public bool ignoreTimeScale = false;
Rigidbody mRb;
Transform mTrans;
void Start ()
{
mTrans = transform;
mRb = GetComponent<Rigidbody>();
}
void Update ()
{
if (mRb == null)
{
ApplyDelta(ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime);
}
}
void FixedUpdate ()
{
if (mRb != null)
{
ApplyDelta(Time.deltaTime);
}
}
public void ApplyDelta (float delta)
{
delta *= Mathf.Rad2Deg * Mathf.PI * 2f;
Quaternion offset = Quaternion.Euler(rotationsPerSecond * delta);
if (mRb == null)
{
mTrans.rotation = mTrans.rotation * offset;
}
else
{
mRb.MoveRotation(mRb.rotation * offset);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cf6484591c9cb0e409f5c53c6978a95d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,29 @@
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Spin With Mouse")]
public class SpinWithMouse : MonoBehaviour
{
public Transform target;
public float speed = 1f;
Transform mTrans;
void Start ()
{
mTrans = transform;
}
void OnDrag (Vector2 delta)
{
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.None;
if (target != null)
{
target.localRotation = Quaternion.Euler(0f, -0.5f * delta.x * speed, 0f) * target.localRotation;
}
else
{
mTrans.localRotation = Quaternion.Euler(0f, -0.5f * delta.x * speed, 0f) * mTrans.localRotation;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d335b6026587ad24dbe124fe5dd1cc02
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,26 @@
using UnityEngine;
/// <summary>
/// This simple example script is used in Tutorial 5 to show how custom events work.
/// </summary>
public class Tutorial5 : MonoBehaviour
{
/// <summary>
/// This function is called by the duration slider. Since it's called by a slider,
/// UIProgressBar.current will contain the caller. It's identical to other NGUI components.
/// A button's callback will set UIButton.current, for example. Input field? UIInput.current, etc.
/// </summary>
public void SetDurationToCurrentProgress (GameObject go=null)
{
UITweener[] tweens = GetComponentsInChildren<UITweener>();
foreach (UITweener tw in tweens)
{
// The slider's value is always limited in 0 to 1 range, however it's trivial to change it.
// For example, to make it range from 2.0 to 0.5 instead, you can do this:
tw.duration = Mathf.Lerp(2.0f, 0.5f, UIProgressBar.current.value);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 94cd518a0b2919a42af43f5184cd1c05
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,56 @@
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script automatically changes the color of the specified sprite based on the value of the slider.
/// </summary>
[AddComponentMenu("NGUI/Examples/Slider Colors")]
public class UISliderColors : MonoBehaviour
{
public UISprite sprite;
public Color[] colors = new Color[] { Color.red, Color.yellow, Color.green };
UIProgressBar mBar;
UIBasicSprite mSprite;
void Start ()
{
mBar = GetComponent<UIProgressBar>();
mSprite = GetComponent<UIBasicSprite>();
Update();
}
void Update ()
{
if (sprite == null || colors.Length == 0) return;
float val = (mBar != null) ? mBar.value : mSprite.fillAmount;
val *= (colors.Length - 1);
int startIndex = Mathf.FloorToInt(val);
Color c = colors[0];
if (startIndex >= 0)
{
if (startIndex + 1 < colors.Length)
{
float factor = (val - startIndex);
c = Color.Lerp(colors[startIndex], colors[startIndex + 1], factor);
}
else if (startIndex < colors.Length)
{
c = colors[startIndex];
}
else c = colors[colors.Length - 1];
}
c.a = sprite.color.a;
sprite.color = c;
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0d15ff9fd80670345b53fd7be4f2f295
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,36 @@
using UnityEngine;
/// <summary>
/// Attaching this script to an object will make it turn as it gets closer to left/right edges of the screen.
/// Look at how it's used in Example 6.
/// </summary>
[AddComponentMenu("NGUI/Examples/Window Auto-Yaw")]
public class WindowAutoYaw : MonoBehaviour
{
public int updateOrder = 0;
public Camera uiCamera;
public float yawAmount = 20f;
Transform mTrans;
void OnDisable ()
{
mTrans.localRotation = Quaternion.identity;
}
void OnEnable ()
{
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
mTrans = transform;
}
void Update ()
{
if (uiCamera != null)
{
Vector3 pos = uiCamera.WorldToViewportPoint(mTrans.position);
mTrans.localRotation = Quaternion.Euler(0f, (pos.x * 2f - 1f) * yawAmount, 0f);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b566c1f22015f644a83ceccc0279fc88
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 100
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,34 @@
using UnityEngine;
/// <summary>
/// Attach this script to a child of a draggable window to make it tilt as it's dragged.
/// Look at how it's used in Example 6.
/// </summary>
[AddComponentMenu("NGUI/Examples/Window Drag Tilt")]
public class WindowDragTilt : MonoBehaviour
{
public int updateOrder = 0;
public float degrees = 30f;
Vector3 mLastPos;
Transform mTrans;
float mAngle = 0f;
void OnEnable ()
{
mTrans = transform;
mLastPos = mTrans.position;
}
void Update ()
{
Vector3 deltaPos = mTrans.position - mLastPos;
mLastPos = mTrans.position;
mAngle += deltaPos.x * degrees;
mAngle = NGUIMath.SpringLerp(mAngle, 0f, 20f, Time.deltaTime);
mTrans.localRotation = Quaternion.Euler(0f, 0f, -mAngle);
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: df649a5c42709b348bc24a4c552ff369
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 200
icon: {instanceID: 0}
userData: