Custom asset type

Hello !

I’m trying to import a custom file into my project, and I’d like to be able to load it from using the AssetDatabase.LoadAssetAtPath() method.
I created a “ScriptedImporter” that loads my file and adds it to the AssetImportContext, but once I want to load it from the path, it returns a null value.

Below, the code I am using:

using System.IO;
using UnityEditor.AssetImporters;
using UnityEngine;

[ScriptedImporter(1, "wrld")]
public class WrldImporter : ScriptedImporter
{
    public override void OnImportAsset(AssetImportContext ctx)
    {
        var asset = ScriptableObject.CreateInstance<WorldFile>();
        asset.name = Path.GetFileNameWithoutExtension(ctx.assetPath);
        // Here I load the content of the file into the current object.
        asset.Initialize(File.OpenRead(ctx.assetPath));

        ctx.AddObjectToAsset("main obj", asset);
        ctx.SetMainObject(asset);
    }
}

Here is my loading code inside of a MonoBehavior:

string mapPath = Path.Combine("Maps", _name);
string wrldFilePath = Path.Combine(mapPath, $"{_name}");
var worldFile = AssetDatabase.LoadAssetAtPath<WorldFile>(wrldFilePath);

Debug.Log(worldFile is null ? "null" : worldFile.name); // always null

Am I doing something wrong? Or maybe I didn’t quite understand the purpose of the ScriptedImporter… :slight_smile:

Hi @Eastrall
Your code seems definitely correct, would it be possible for you to report a bug with your project so we could have a closer look at what’s happening?
Feel free to reply here with the bug number when you post it so I can have a look at it as soon as possible.

1 Like

Thank you for your reply. I figured it out today, I managed to load it correctly, not really sure why it was not loading properly. When loading, my data was always at 0 (default values). And I realized that I was using properties with “get; private set;” to store my data I am loading from my file. So, I used private fields with the [SerializeField].

Problem solved. Thank you for taking the time to reply to my issue. :slight_smile:

1 Like