/*
* hierarchy路径属性
*
* 可以在指定类上边使用此属性
*
* 在创建时利用反射找此属性下的path
*
* 最后构建物体
*
* ps:此类可以作为基类继承使用
*
*/
[AttributeUsage(AttributeTargets.Class)]
public class HierarchyPath : Attribute
{
private string mPath;
public string Path
{
get { return mPath; }
}
public HierarchyPath(string path)
{
mPath = path;
}
}
//外部使用方法---------------------------------------------------------------------
[HierarchyPath("[MyRoot]/Test/Fuck/HierarchyUsage")]
public class HierarchyUsage : MonoBehaviour
{
private static HierarchyUsage instance = null;
private static readonly object Lock = new object();
public static HierarchyUsage Instance
{
get
{
lock (Lock)
{
if (instance == null)
{
GameObject parent = null;
Transform temp = null;
string name = null;
Type type = typeof(HierarchyUsage);
name = type.Name;
/*
* 反射查找指定属性
*
* 对属性进行解析,然后配置路径
*
* 最后对目标文件赋值
*
* 这里简单演示属性的作用
*
* 并没有对其进行相应封装以及提取
*
* 需要自行提取
*
* ------------------------------------------------------------------------------
*/
object[] attributes = type.GetCustomAttributes(false);
if (attributes != null && attributes.Length > 0)
{
foreach (var item in attributes)
{
HierarchyPath hierarchy = item as HierarchyPath;
if (hierarchy != null)
{
string[] paths = hierarchy.Path.Split('/');
int index = 0;
if (paths != null && paths.Length > 0)
{
while (index < paths.Length - 1)
{
if (parent == null)
{
parent = GameObject.Find(paths[index]);
if (parent == null)
{
parent = new GameObject(paths[index]);
}
}
else
{
temp = parent.transform.Find(paths[index]);
if (temp == null)
{
temp = new GameObject(paths[index]).transform;
temp.SetParent(parent.transform);
}
parent = temp.gameObject;
}
++index;
}
}
}
}
}
/*
* ------------------------------------------------------------------------------
*/
instance = new GameObject(name).AddComponent<HierarchyUsage>();
instance.transform.SetParent(parent == null ? null : parent.transform);
}
return instance;
}
}
}
public HierarchyUsage()
{
if (instance != null)
{
Debug.Log("error >> more singleton");
}
}
private void Awake()
{
instance = this;
}
public void Show()
{
Debug.Log("请查看详细hierarchy路劲");
}
}
//外部使用方法---------------------------------------------------------------------
这样就可以分配好物体路径了
目前仍然是简易版
需要更加进一步提取以及高度运用