ScriptableObject Referencing
Hi,
I'm having a small conceptual problem with SO's. If I create an SO like thus...
[CreateAssetMenu(menuName = "Node / Archetype")]
public class NodeTypeArc : ScriptableObject
{
public string Test;
}
I then generate, via the asset menu, a number of instance of this SO, eg. "Utility", "Corporate", "Government", "Research", which all appear in the Project view.
I understand that I can then drag and drop these instances across to a Monobehaviour script in the Inspector anywhere I have a public NodeTypeArc instance.
Q1: All good but is there a way to directly access the specific SO instances, eg. "Corporate", from code?
I realise I can easily do this...
node.instance = ScriptableObject.CreateInstance<NodeTypeArc>();
but that doesn't get me the "Corporate" SO instance that I'm after.
Q2: Would I be correct in thinking that what I want could only be done by deriving from my NodeTypeArc SO class?, eg.
public class Corporate : NodeTypeArc
and then doing this...
node.instance = ScriptableObject.CreateInstance<Corporate>();
If somebody could point me in the right direction here it'd be appreciated.
Cheers,
Cameron
Answer by plugger22 · Oct 11, 2017 at 05:24 AM
I'll self answer this one.
AssetsDatabase.FindAssets does the job. The documentation is comphrensive but here's a quick snippet.
@MenuItem("Test/FindAssetsUsingSearchFilter")
static function FindAssetsUsingSearchFilter ()
{
// Find all assets labelled with 'concrete' :
var guids = AssetDatabase.FindAssets ("l:concrete", null);
for (var guid in guids)
Debug.Log (AssetDatabase.GUIDToAssetPath(guid));
// Find all Texture2Ds that have 'co' in their filename, that are labelled with 'concrete' or 'architecture' and are placed in 'MyAwesomeProps' folder
var guids2 = AssetDatabase.FindAssets ("co l:concrete l:architecture t:texture2D", ["Assets/MyAwesomeProps"]);
for (var guid in guids2)
Debug.Log (AssetDatabase.GUIDToAssetPath(guid));
}
By finding the SO, then getting it's asset path, you can load it directly from script.
Cheers, Cameron
Were you able to use class Corporate directly in your code? If so, could you post code to show what you did?
AssetDatabase will only work in the editor, not standalone builds. You could use Resources.Load, but Unity recommends only doing so for prototyping or small, rare instances, as the cost of loading from Resources does not scale.