Search code examples
c#fileunity-game-enginesaveassets

Is there any way to determine the extent of an asset based on the type of object that is received?


I would like to know if there is any way to create an asset in Unity simply by passing an Object and that the extension could be determined without having to go one by one checking with getType if it is of one type or another to put one extension or another, here is a example:

public void SaveAsset(Object obj)
{
   string ext = ""; //How to get this?
   AssetDatabase.CreateAsset(obj, "Assets/" + obj.name + ext);
}

Solution

  • No, afaik you would have to go by type .. the list of checks seems quite limited though:

    '.mat' for materials, '.cubemap' for cubemaps, '.GUISkin' for skins, '.anim' for animations and '.asset' for arbitrary other assets.

    so in most cases it will simply be .asset except you are doing fancy stuff ;)

    having to go one by one checking with getType

    actually that's not the case anymore! I think since c# 7 you can use a type based switch like e.g.

    string ext;
    switch(obj)
    {
        case Material:
            ext = ".mat";
            break;
    
        case Cubemap:
            ext = ".Cubemap";
            break;
    
        case GUISkin:
            ext = ".GUISkin";
            break;
    
        case AnimationClip:
            ext = ".anim";
            break;
    
        default:
            ext = ".asset";
            break;
    }
    

    Basically this equals more or less writing

    string ext;
    if(obj is Material)
    {
        ext = ".mat";
    }
    else if(obj is Cubemap)
    {
        ext = ".Cubemap";
    }
    else if(obj is GUISkin)
    {
        ext = ".GUISkin";
    }
    else if(obj is AnimationClip)
    {
        ext = ".anim";
    }
    else 
    {
        ext = ".asset";
    }
    

    see also Tutorial: Use pattern matching to build type-driven and data-driven algorithms so latest in c# 8 you can write the same thing also as a Pattern Matching like e.g. (though I don't like that too much)

    var ext = obj switch
    {
        Material _ => ".mat",
        Cubemap _ => ".cubemap",
        GUISkin _ => ".GUISkin",
        AnimationClip _ => ".anim",
        _ => ".asset"
    };
    

    Since anyway your code will only be running in the Editor itself (somewhere else the AssetDatabase is not available) the performance shouldn't be your concern since it doesn't need to be realtime.