- Home /
How to load an asset without a reference?
I implemented a basic editor extension to help me with some of the workflows of my project. I needed this extension to be loaded without any user interaction, i.e. no custom prefabs or scripts in the scene and no EditorWindow. To achieve this I annotated a class with InitializeOnLoad and subscribed to some editor events.
This works pretty well, but now I need to render some small sprites on the scene view and I'm having trouble accessing the textures to do that. Since I'm not using a MonoBehaviour or ScriptableObject for this extension, I probably can't set up a reference to those assets anywhere.
I could load them from a hard coded path using AssetDatabase.LoadAssetAtPath, but that doesn't seem to be a good idea either. If I were to ever release this asset, the user couldn't move it anywhere from the hard coded path.
Answer by Bill9009 · May 29, 2017 at 07:13 AM
Would the user need to move it from the hard coded path?
Some people like to move all their downloaded assets to an "External" or "ThirdParty" folder. So I'm wondering how published assets can load their own resources without breaking when the user moves everything to a different folder.
You could directly use the GUID's to find the assets. As long as the Assets are in the Assets folder you can use:
AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath("GUID Here"))
To get the GUID open the .meta file associated with the file being opened. This will only work in the editor however.
Wouldn't the GUID be different for every user? I believe the GUID is generated during import. So I would have to find the asset first to get the GUID, but that's what I'm having trouble with.
Answer by PizzaPie · May 29, 2017 at 10:40 AM
I am using something like this ->
string[] guids = AssetDatabase.FindAssets("t:MyClassType"); //see the docs for the tags (t:) means looking for type
if (guids.Length == 0)
return;
for(int i = 0; i < guids.Length; i++)
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
list.Add((MyClassType)AssetDatabase.LoadAssetAtPath(path, typeof(MyClassType))); //list typeof MyClassType
}
That finds reference/loads all assets typeof MyClassType.Probably there are other ways too. Cheers.
Edit: We are talking about editor time and not runtime, right?
Your answer
Follow this Question
Related Questions
Error using ImportAssetOptions.ForceSynchronousImport 2 Answers
Unity recompilation time slowly increases each time it's recompiled. Why? 0 Answers
Loading subassets at runtime 1 Answer
How do I import assets from the Asset Store while offline? 2 Answers
AssetGraph bug fixed request(Override Import Setting doesn't work) 0 Answers