- Home /
Null Reference Error With Scriptable Objects
Custom Scriptable Object
public class GameDataScriptableObject<T>: ScriptableObject,ICSVReader where T : class
{
public T[] mData;
public T GetFromId(uint ID)
{
for (int i = 0; i < mData.Length; ++i)
{
var data = mData as IReturnID;
if (data.GetID() == ID)
return mData;
}
return default(T);
}
public GameDataScriptableObject()
{
}
public GameDataScriptableObject(T obj)
{
}
public void ParseCSV(string data)
{
var engine = new FileHelperEngine<T>();
mData = engine.ReadString(data);
}
}
Interface
public interface ICSVReader
{
void ParseCSV(string data);
}
Helper Function
public static UnityEngine.Object CreateAsset<T>(string assetFileName) where T : ScriptableObject
{
var scriptableObject = ScriptableObject.CreateInstance<T>();
TextAsset csvAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>(TextAssetDataLocation + assetFileName + InputAssetFileExtension);
if (scriptableObject == null)
Debug.Log("NULL");
var parser = scriptableObject as ICSVReader;
parser.ParseCSV(csvAsset.text);
UnityEditor.AssetDatabase.CreateAsset(scriptableObject, AssetDataBaseLocation + assetFileName + AssetFileExtension);
UnityEditor.AssetDatabase.SaveAssets();
return scriptableObject;
}
i have written a helper function to create an ScriptableObject from a csv file My problem is.... whenever i call
CreateAsset<GameDataScriptableObject<EachSkill>>("EnemyData"); // EnemyData is the name of the text file and eachskill is a data structure
i get an error !!!! here "parser.ParseCSV(csvAsset.text);" - > Debug Prints "NULL" which means ScriptableObject.CreateInstance failed... how ever if i have a class like this
public class EnemyData : GameDataScriptableObject<EachSkill>
{
}
and if i call the same function again like this
CreateAsset<EnemyData >("EnemyData");
It Works Perfectly!!!!!!
What am i doing wrong here? and why is the code behaving like this.? Any sort of help would be really helpful!
Answer by Bunny83 · Dec 26, 2015 at 11:25 AM
ScriptableObjects have the same restriction as MonoBehaviour classes. They must be non generic and each class need to be placed in a file where the file name matches the classname. Otherwise the serialization system in the editor doesn't work.
So you have to create concrete non-generic subclasses for each of your cases.
@Bunny83 hey thanks for getting back! is there any other way for me to do it? when i read back from the asset file i dont need to save it to something like "EnemyData" but rather i can read it directly into "GameDataScriptableObject>".. why is that!??
Use comments and not answers when you don't have an answer!!! Converted to comment.
thanks for pointing out... this js my first rodeo. will be careful.