Search Unity

Question Creating a ScriptableObject with initial stored data through code.

Discussion in 'Prefabs' started by Techeart, Apr 29, 2021.

  1. Techeart

    Techeart

    Joined:
    Dec 29, 2019
    Posts:
    3
    I have a script that, when a button is clicked, creates a ScriptableObject and stores it in assets. When creating an object, I calling its internal Init method, which should write data to the created object. But, when I trying to get this data from it, I only receiving null. So, how can I then write information to the ScriptableObject when it is created?

    My ScriptableObjerct:
    Code (CSharp):
    1. [CreateAssetMenu(fileName = "Animations Analyzer", menuName = "MotionMatching/AnimationsData")]
    2. public class AnimationsDataStorage : ScriptableObject
    3. {
    4.     public KeyframeInfo[] storedData;
    5.  
    6.     public void Init(List<KeyframeInfo> data)
    7.     {
    8.         storedData = data.ToArray();
    9.     }
    10.  
    11.     public KeyframeInfo[] GetData()
    12.     {
    13.         return storedData;
    14.     }
    15. }
    SO creating code:
    Code (CSharp):
    1. private void CreateAsset()
    2.     {
    3.         AnimationsDataStorage asset = ScriptableObject.CreateInstance<AnimationsDataStorage>();
    4.         asset.Init(keyframesDatabase);
    5.         ProjectWindowUtil.CreateAsset(asset, "AnimationsData.asset");
    6.         AssetDatabase.SaveAssets();
    7.         EditorUtility.FocusProjectWindow();
    8.         Selection.activeObject = asset;
    9.     }