2023-04-03 11:04:31 +08:00

82 lines
2.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BF
{
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class BFCircleLayout : MonoBehaviour
{
public float radius = 100;
[Range(0, 360)]
public float startAngle = 0;
[Range(0, 360)]
public float angle = 30;
public int ActiveCount
{
get
{
var result = 0;
for (var i = 0; i < rectTransform.childCount; i++)
{
var t = rectTransform.GetChild(i);
if (t != null && t.gameObject.activeInHierarchy)
{
result++;
}
}
return result;
}
}
RectTransform rectTransform;
List<RectTransform> children = new List<RectTransform>(4);
void Start()
{
rectTransform = GetComponent<RectTransform>();
Relayout();
}
void OnValidate()
{
Relayout();
}
public void Relayout()
{
#if UNITY_EDITOR
if (rectTransform == null)
{
return;
}
#endif
children.Clear();
for (var i = 0; i < rectTransform.childCount; i++)
{
var rect = (RectTransform)rectTransform.GetChild(i);
if (rect != null && rect.gameObject.activeInHierarchy)
{
children.Add(rect);
}
}
var length = children.Count;
for (int i = 0; i < length; i++)
{
var t = children[i];
t.anchoredPosition = GetPosByIndex(i);
}
}
public Vector2 GetPosByIndex(int index)
{
var a = Mathf.Deg2Rad * (index * angle + startAngle);
var pos = new Vector2(radius * Mathf.Cos(a), Mathf.Sin(a) * radius);
return pos;
}
}
}