如何在场景中找到附加到游戏对象的所有类型的脚本?

问题描述 投票:0回答:1
    static List<string> scriptsNames = new List<string>();
    
    [MenuItem("Window/Autocomplete Searchbar/AssetDatabase Search Example")]
    static void Init()
    {
        GetWindow<AssetDatabaseSearchExample>("AssetDatabase Example").Show();
    
        MonoBehaviour[] scripts = UnityEngine.Object.FindObjectsOfType<MonoBehaviour>();
        foreach (MonoBehaviour script in scripts)
        {
            Type scriptType = script.GetType();
            var scope = scriptType.Namespace;
            if (scope == null || !scope.StartsWith("Unity"))
            {
                scriptsNames.Add(scriptType.Name);
            }
            //Debug.Log(script.GetType().FullName + " is used within " + script.gameObject.name);
        }
    }

目标是找到所有脚本和所属的游戏对象,并通过列表或字典显示它

c# unity3d
1个回答
1
投票

未设置的代码,稍后会正确测试,

我会做类似的事情

var monobaviours = gameobject.GetComponents<Monobehaviour>(); 

获取所有自定义单一行为脚本,或者简单地

var compoments = gameobject.GetComponents<Component>();

这应该让您获得附加到特定游戏对象的任何类型的所有组件

如果你想让他们都在一个场景中,你可以这样做

Dictionary<GameObject, list<Type>> scriptsDict = new();
var allGameObjects = UnityEngine.Object.FindObjectsOfType<GameObject>(); 
foreach(var go in allGameObjects)
{
    var monobaviours = gameobject.GetComponents<Monobehaviour>();
    scriptsDict.Add(go, monobaviours.select(m => typeof(m)).ToList(); // off my head, may need tinkering
}

或者如果您只想将脚本作为实际实例

Dictionary<GameObject, list<MonoBehaviour>> scriptsDict = new();
var allGameObjects = UnityEngine.Object.FindObjectsOfType<GameObject>()); 
foreach(var go in allGameObjects)
{        
    var monobaviours = gameobject.GetComponents<Monobehaviour>();
    scriptsDict.Add(go, monobaviours.ToList());
}
© www.soinside.com 2019 - 2024. All rights reserved.