using UnityEngine;
using System.Collections.Generic;
[ExecuteInEditMode]
public class UIGridPlus : MonoBehaviour {
public enum Pivot {
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottomCenter,
BottomRight
}
public Pivot pivot;
public int maxPerLine = 0;
public float cellWidth = 200f;
public float cellHeight = 200f;
public bool repositionNow = false;
public bool sorted = false;
public bool hideInactive = true;
bool mStarted = false;
void Start() {
mStarted = true;
Reposition();
}
void Update() {
if (repositionNow) {
repositionNow = false;
Reposition();
}
}
static public int SortByName(Transform a, Transform b) { return string.Compare(a.name, b.name); }
/// <summary>
/// Recalculate the position of all elements within the grid, sorting them alphabetically if necessary.
/// </summary>
public void Reposition() {
if (!mStarted) {
repositionNow = true;
return;
}
Transform myTrans = transform;
int x = 0;
int y = 0;
List
<Transform
> list
= new List
<Transform
>();
for (int i = 0; i < myTrans.childCount; ++i) {
Transform t = myTrans.GetChild(i);
if (t && (!hideInactive || NGUITools.GetActive(t.gameObject))) list.Add(t);
}
if (sorted) {
list.Sort(SortByName);
}
int lines = maxPerLine > 0 ? list.Count / maxPerLine - 1 : 0;
int columns = maxPerLine > 0 ?
(list.Count > maxPerLine ? maxPerLine : list.Count) - 1 :
list.Count - 1;
Debug.Log(lines + " " + columns);
for (int i = 0, imax = list.Count; i < imax; ++i) {
Transform t = list[i];
if (!NGUITools.GetActive(t.gameObject) && hideInactive) continue;
float depth = t.localPosition.z;
Vector3 newPos
= new Vector3
(); switch (pivot) {
case Pivot.TopLeft:
case Pivot.TopCenter:
case Pivot.TopRight:
newPos.y = -cellHeight * y;
break;
case Pivot.MiddleLeft:
case Pivot.MiddleCenter:
case Pivot.MiddleRight:
newPos.y = -cellHeight * (-lines / 2f + y);
break;
case Pivot.BottomLeft:
case Pivot.BottomCenter:
case Pivot.BottomRight:
newPos.y = cellHeight * (lines - y);// -cellHeight * lines + cellHeight * y;
break;
default:
break;
}
switch (pivot) {
case Pivot.TopLeft:
case Pivot.MiddleLeft:
case Pivot.BottomLeft:
newPos.x = cellWidth * x;
break;
case Pivot.TopCenter:
case Pivot.MiddleCenter:
case Pivot.BottomCenter:
newPos.x = cellWidth * (-columns / 2f + x); // -cellWidth * (columns / 2f) + cellWidth * x;
break;
case Pivot.TopRight:
case Pivot.MiddleRight:
case Pivot.BottomRight:
newPos.x = cellWidth * (-columns + x);
break;
default:
break;
}
newPos.z = depth;
t.localPosition = newPos;
if (++x >= maxPerLine && maxPerLine > 0) {
x = 0;
++y;
}
}
UIDraggablePanel drag = NGUITools.FindInParents<UIDraggablePanel>(gameObject);
if (drag != null) drag.UpdateScrollbars(true);
}
}