I was trying to do a Translation System with properties, those properties i need that they can be of any type then i used generics, but for some reason unity can’t serialize them, here the files:
Base Class
using System;
using UnityEngine;
[Serializable]
public abstract class TranslationProperty : ScriptableObject
{
[field: SerializeField]
public string Name { get; protected set; }
public abstract void SetValue(object newValue);
public abstract object GetValue();
public static T CreateInstance<T>(string name, string value) where T : TranslationProperty
{
var instance = CreateInstance<T>();
instance.Name = name;
instance.init(value);
return instance;
}
protected abstract void init(string value);
public abstract TranslationProperty Clone();
#if UNITY_EDITOR
public bool Foldout = false;
public abstract void OnInspector();
#endif
}
Generic Class
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
[Serializable]
public abstract class TranslationProperty<T> : TranslationProperty
{
[field: SerializeField]
public T Value { get; set; }
public override object GetValue()
=> Value;
public override void SetValue(object newValue)
=> Value = (T)newValue;
public abstract T Parse(string value);
public override TranslationProperty Clone()
{
TranslationProperty<T> instance = (TranslationProperty<T>)getInstance();
instance.Name = Name;
instance.SetValue(Value);
return instance;
}
protected abstract TranslationProperty getInstance();
public override string ToString()
{
return Value.ToString();
}
protected override void init(string value)
{
Value = Parse(value);
}
#if UNITY_EDITOR
public override void OnInspector()
{
EditorGUILayout.LabelField($"Property {Name}");
}
#endif
}
SubClass:
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
[Serializable]
public class IntProp : TranslationProperty<int>
{
public override int Parse(string value)
=> int.Parse(value);
protected override TranslationProperty getInstance()
=> CreateInstance<IntProp>();
#if UNITY_EDITOR
public override void OnInspector()
{
EditorGUILayout.BeginHorizontal();
base.OnInspector();
Value = EditorGUILayout.IntField(Value);
EditorGUILayout.EndHorizontal();
}
#endif
}
I really don’t know what is failing because all properties/fields have the SerializeField, the base class inherit from ScriptableObject and all use [Serializable].
For this i did a test class:
using UnityEngine;
public class TestTranslation : MonoBehaviour
{
public IntProp prop;
}
Also an editor for that test:
using UnityEditor;
[CustomEditor(typeof(TestTranslation))]
[CanEditMultipleObjects]
public class TestTranslationEditor : Editor
{
public override void OnInspectorGUI()
{
TestTranslation t = (TestTranslation)target;
if (t.prop == null)
t.prop = TranslationProp.CreateInstance<IntProp>("prop1", "0");
t.prop.OnInspector();
EditorUtility.SetDirty(t);
}
}
I would like that the property is serialized correctly.