UnityInspector給元件自動關聯引用

1405048499729402發表於2019-02-14

通過宣告的變數名稱,主動關聯引用.
使用這個關聯引用兩種方式

  1. 給你元件繼承 MonoAutoQuote 點選元件inspector 按鈕執行
  2. 給你元件類新增[AAutoQuote] 特性 通過Plateface/SetSelectGameRef 執行

[AAutoQuote]public class MonoAutoQuote : MonoBehaviour ,IAutoQuote{}
public interface IAutoQuote { }
public class AAutoQuote : Attribute {}

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEditor;using System.Reflection;

//[CanEditMultipleObjects]
[CustomEditor(typeof(MonoAutoQuote), true)]public class AutoQuoteEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();

if (GUILayout.Button(“關聯子節點引用”))
{
Component c = target as Component;
if (c != null)
AutioQuoteMenu.SetRef(c, c.gameObject);
}

}
}
public class AutioQuoteMenu
{
[MenuItem(“Plateface/SetSelectGameRef %&A”)]
public static void SetRef()
{
GameObject o = Selection.activeGameObject;
if (o != null)
{
Component[] cAry = o.GetComponents();
foreach (var c in cAry)
{
System.Type componentType = c.GetType();
if ((typeof(MonoBehaviour).IsAssignableFrom(componentType)) || IsHasAttribute(componentType))
{
SetRef(c, o);
}
}
}
}

public static void SetRef(Component c, GameObject o)
{
System.Type t = c.GetType();
var infoList = t.GetFields(BindingFlags.Public | BindingFlags.Instance);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string name = string.Empty;
foreach (var item in infoList)
{
var fieldType = item.FieldType;

if ((typeof(MonoBehaviour).IsAssignableFrom(fieldType)))
{
if (item.Name.StartsWith(“m”))
{
name = item.Name.Substring(1);
Transform tr = o.transform.Find(name);
if (tr == null)
{
Debug.LogError(name + “引用沒找到”);
continue;
}

Component com = tr.GetComponent(fieldType);
item.SetValue(c, com);
}
}
}
}

public static bool IsHasAttribute(System.Type type)
{
System.Object[] oList = type.GetCustomAttributes(typeof(AAutoQuote), false);
foreach (var item in oList)
{
if ((item as AAutoQuote) != null)
return true;
}

return false;
}
}

更多unity2018的功能介紹請到paws3d學習中心查詢。


相關文章