0
\$\begingroup\$

I am trying to find all types that inherit from monobehaviour inside my Unity project. So not the instances of them but the actual types in the assembly. I've tried this little piece of code and I don't understand why it is not getting the types. The debug is logging 0.

Also I am going to use this in editor scripting. But for testing purposes I am running the code in the start method of a component.

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

public class TypeGetter : MonoBehaviour
{
    private Dictionary<Type, FieldInfo[]> monobehavioursInfo = new Dictionary<Type, FieldInfo[]>();

    private void Start()
    {
        monobehavioursInfo = GetTypes<MonoBehaviour>();
        Debug.Log(monobehavioursInfo.Count);
    }

    private Dictionary<Type, FieldInfo[]> GetTypes<T>()
    {
        Dictionary<Type, FieldInfo[]> temp = new Dictionary<Type, FieldInfo[]>();
        foreach (Type t in Assembly.GetAssembly(typeof(T)).GetTypes()
            .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
        {
            FieldInfo[] fields = t.GetFields();
            temp.Add(t, fields);
        }
        return temp;
    }
}
\$\endgroup\$
0
\$\begingroup\$

My guess is that MonoBehaviour is not in the assembly-csharp assembly. Try Assembly.GetAssembly(this.type). Although this won’t work once this code goes into an editor script, because the editor script goes into a different assembly on its own. In that case, you would probably just want to use typeof(SomeInGameType)

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.