- Home /
Referencing / linking a .asset / .prefab file in another .asset / .prefab file programmatically.
Hi,
Actually I've asked this on the forum but no one answered. So here goes...
I wanted to make an Editor Window that can automate the whole creation of an asset file from a configuration file. So I can create the asset file from ScriptableObject.CreateInstance
and the the AssetDatabase.CreateAsset
methods. But how do I reference another .asset file or .prefab file that is in the same Project folder into it (ie. similar with dragging it to the created .asset file) from the code?
I need it because the asset files are actually linked list entries. I need to have, eg. asset1 linked to asset2, asset2 to asset3, etc. So I can iterate between the data stored in the .asset files based on it's chain. And like the creation, the linkage of the asset files should be automated from a configuration files like the asset's creation.
The other reason is, I also need to be able to reference a prefab file in the project's folder automatically as a variable of the .asset file. Which should be searched throughout the project folders automatically. And again, based on a configuration file.
My instinct says it has got to do with the Assemblies. But how exactly do I do it?
Thanks in advance.
Answer by _dns_ · Feb 01, 2016 at 03:38 PM
To assign a prefab/asset to another object's serializable field, the prefab/asset must be loaded with AssetDatabase.LoadAssetAtPath (or similar methods) and then assigned to the field. Unity will take care of the rest for the serialization of the newly created object. You should also use EditorUtility.SetDirty on the modified object to tell unity that it will need to re-serialize it the next time the scene/project is saved.
Answer by winxalex · Feb 14, 2018 at 02:27 PM
MyAssetType myAsset=ScriptableObject.CreateInstance<MyAssetType>();
AssetDatabase.AddObjectToAsset(prefab, myAsset);
myAsset.referencing=prefab;
// same with 2 assets, prefab in asset, asset in prefab, as prefab actually is another Asset