I am trying to create a tool for creating game items in Unity. I started by creating a base class from which all game elements in the game are inherited:
[System.Serializable]
public class ItemModel
{
public int ID;
public string Name;
public string Description;
public UnityEngine.Sprite Picture;
public int Cost;
public float Weight;
}
Then, based on the base class, several classes were created for a specific type of item (such as a weapon class):
using UnityEngine;
using System;
[Serializable]
public class WeaponModel : ItemModel
{
[Range(0, 10000)] int Damage;
}
To save data about this item, you need to use a ScriptableObject, and here I created a variable of type Object to store all the specific classes about the game item in it:
using System;
using UnityEngine;
[System.Serializable]
public enum ItemType
{
Default,
Weapon,
Armory,
Potion,
Food,
Readable
}
[Serializable]
public class ItemData : ScriptableObject
{
public ItemType Type;
public System.Object Item;
public GameObject Prefab;
}
But this solution is not correct for EditorGUILayout.PropertyField (), since it will draw exactly the type Object and will not allow me to add the class I need. Then I tried, depending on the enum ItemType, to set the needed class into Object using the following method:
protected void DrawNoSerializedField<T, T2>(System.Object obj)
{
Type objType = typeof(T);
FieldInfo[] varsArray = objType.GetFields();
for (int i = 0; i < varsArray.Length; i++)
{
if(varsArray[i].FieldType == typeof( System.Object))
{
Type Ttype = typeof(T2);
System.Object instance = Activator.CreateInstance(Ttype);
varsArray[i].SetValue(instance, null);
}
}
}
And call it like this:
ItemData data = _window.serializedObject.targetObject as ItemData;
DrawNoSerializedField<ItemData, WeaponModel>(data);
But at the moment varsArray[i].SetValue(instance, null) Unity throws an error MissingMethodException: Default constructor not found for type WeaponModel.
I can refuse the idea with inherited object classes, but in this case, you lost the specificity of the created game item.
In that case, how do I organize the base item classes so that I can create specific items like Weapons or Armor and save them as ScriptableObject and implement it all in a separate window as EditorGUILayout in Unity?