Load an Scriptable Object from string?
I can see that the scriptable objects are stored as .asset files Which are just YAML files. Is it possible to load a YAML file content(as string) into a Scriptable Object at runtime in published game?
Answer by rage_co · Sep 01, 2021 at 04:10 AM
So here's something i came up with
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class AssetReader : MonoBehaviour
{
public ToImport[] toimport;
public List<Object> createdObjects = new List<Object>();
public string assetPath;
public void LoadAll()
{
foreach(ToImport object in toimport)
{
CreateNew(object.path, object.name);
}
}
public void LoadParticular(int i)
{
CreateNew(toimport[i].path, toimport[i].name);
}
public void CreateNew(string path, string name)
{
if(!File.Exists(path))
{
Debug.LogWarning("no file exists at " + path);
return;
}
else
{
string contents = File.ReadAllText(path);
AssetDatabase.CreateAsset(Object, "Assets/" + assetPath + name + ".asset");
Object object = Resources.Load<Object>("Assets/" + assetPath + name + ".asset");
object.text = contents;
createdObjects.Add(object);
Debug.Log("Asset named " + name + " at path : " + path + "has been loaded successfully");
}
}
}
[System.Serializable]
public class ToImport
{
public string name;
public string path;
}
this script should be able to load scriptable objects from the text or YAML file at runtime, although it won't be able to save them in build due to obvious reasons....so you need to load them up everytime the application starts in the build, you can use the json utility to save any scriptable objects you create during runtime.....also, this may result in cluttering of the assets folder in editor since the files are automatically saved in the editor....also don't forget to replace they type 'Object' with the type you want to work with, i think even using ScriptableObject as they type should work as a universal scriptableobject reference...hope this helps...and works too