- Home /
Detecting Asset Types
Suppose I have a path to a folder of assets , the types of which are unknown. and I want to determine if each one of the assets is a Texture, Model, or Audio etc. and then do further editor script things to it depending on type.
how would I do this? If I use AssetDatabaseGetAssetAtPath() I must cast it to a certain type.
What if I don't know an assets type ahead of time? Unity assigns correct thumbnail icons to each type, therefore it must have some detection happening. Is that code available to us?
Answer by Centripetal · May 21, 2020 at 04:56 PM
To get the type of a ScriptableObject type where the class is called "MyClass" you can do the following:
[MenuItem("Assets/Do Something Cool")]
private static void DoSomethingCool()
{
Debug.Log("OOOOoooh so COOL!!!!");
}
[MenuItem("Assets/Do Something Cool", true)]
private static bool DoSomethingCoolValidate()
{
if (!(Selection.activeObject is MonoScript))
{
return false;
}
return ((MonoScript)Selection.activeObject).GetClass() == typeof(MyClass);
}
Answer by Vatio · Feb 14, 2017 at 09:00 AM
Since Unity 5.5 there is the function: AssetDatabase.GetMainAssetTypeAtPath(string assetPath);
https://docs.unity3d.com/ScriptReference/AssetDatabase.GetMainAssetTypeAtPath.html
There is however an issue with this function. It is broken for for all asset types derived from ScriptableObject: for these, it will always return $$anonymous$$onoBehaviour ins$$anonymous$$d of the actual type, even though the asset doesn't even derive from $$anonymous$$onoBehaviour!
The issue is fixed in 2017.1.0b9
See issue tracker link below: https://issuetracker.unity3d.com/issues/assetdatabase-dot-getmainassettypeatpath-returns-monobehaviour-for-scriptableobjects