- Home /
how to save instance of class trough editor
I've made a script witch lets you make instances of a class in the inspector. It all works inside the editor, but i can't wrap my head around saving the data, i'm not sure what to use? SetDirty? Here is my code, if you need other scripts for clarification pleas ask!
using UnityEngine;
using System.Collections;
using System.Reflection;
using UnityEditor;
[CustomEditor(typeof(InstanceGenerator) )]
public class InstanceCreatorEditor : Editor {
public override void OnInspectorGUI ()
{
//base.OnInspectorGUI ();
InstanceGenerator ig = (InstanceGenerator)target;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Instance Type: ");
ig.currType = (Items.instanceTypes)EditorGUILayout.EnumPopup(ig.currType);
EditorGUILayout.EndHorizontal();
if(GUILayout.Button("Generate new Instance.") )
{
if(ig.currType == Items.instanceTypes.item)
{
ig.genStat = new Item(0,0,0,"");
}
if(ig.currType == Items.instanceTypes.enemy)
{
ig.genStat = new BaseCharacter(0,0,0,0,0);
}
}
EditorGUILayout.Space();
var myType = ig.genStat.GetType();
PropertyInfo[] properties = myType.GetProperties();
foreach(PropertyInfo property in properties)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(property.Name);
object value = property.GetValue(ig.genStat, null);
if(value is int)
{
property.SetValue(ig.genStat, EditorGUILayout.IntField((int)value), null);
}
if(value is string)
{
property.SetValue(ig.genStat, EditorGUILayout.TextField((string)value), null);
}
if(value is float)
{
property.SetValue(ig.genStat, EditorGUILayout.FloatField((float)value), null);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Space();
if(GUILayout.Button("Save generated instance.") )
{
ig.GenerateInstance();
////Save data Here!
}
}
}
Comment
Answer by RudyTheDev · Feb 20, 2014 at 05:53 PM
I'm not sure what exactly ig.GenerateInstance()
creates. In any case, you probably either want ScriptableObject
s or custom assets (made with various AssetDatabase
functions for this, like AssetDatabase.CreateAsset()
). Unity can't save a parent-less class unless you attach it to something it understands (and can serialize) - scene game object, prefab or asset.