Unity技术分享征服Unity3d技术干货

引用分析

2016-06-02  本文已影响559人  2b75747cf703

http://answers.unity3d.com/questions/321615/code-to-mimic-find-references-in-scene.html
TransformExtension http://www.jianshu.com/p/7eaf986876b6

Unity编辑器非常强大,开发过程中,经常拖拉各种组件引用。
最终可能引用十分混乱,那么这时候就需要用到引用分析,不然场景中一个个自己去找蛋都要碎了。

Paste_Image.png

比如我想查找Demo这个组件被那些对象引用。。

Paste_Image.png

点击Log,可以看到相应的资源。

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using Babybus.Framework.ExtensionMethods;

namespace Babybus.Framework.Extension
{
    public class FindReferences
    {
        [MenuItem("CONTEXT/Component/Find references to this")]
        private static void FindReferencesToComponent(MenuCommand command)
        {
            FindReferencesTo(command.context);
        }

        [MenuItem("Assets/Find references to this")]
        private static void FindReferencesToAsset()
        {
            foreach (var assetObject in Selection.objects)
            {
                FindReferencesTo(assetObject);
            }
        }

        private static void FindReferencesTo(Object to)
        {
            if (to == null)
                return;

            var referencedBy = new List<Object>();
            var allObjects = Object.FindObjectsOfType<GameObject>();

            foreach (var go in allObjects)
            {
                if (PrefabUtility.GetPrefabType(go) == PrefabType.PrefabInstance)
                {
                    if (PrefabUtility.GetPrefabParent(go) == to)
                    {
                        Debug.Log(string.Format("{0} referenced by {1}, {2}", to, go.transform.GetPath(), go.GetType()), go);
                        referencedBy.Add(go);
                    }

                    continue;
                }

                var components = go.GetComponents<Component>();
                foreach (var component in components)
                {
                    var iterator = new SerializedObject(component).GetIterator();

                    while (iterator.NextVisible(true))
                    {
                        if (iterator.propertyType == SerializedPropertyType.ObjectReference)
                        {
                            if (iterator.objectReferenceValue == to)
                            {
                                Debug.Log(string.Format("{0} referenced by {1}, {2}", to, component.transform.GetPath(), component.GetType()), component);
                                referencedBy.Add(component);
                            }
                        }
                    }
                }
            }

            if (referencedBy.Count == 0)
                Debug.Log(to + " no references in scene");
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读