Custom PropertyDrawer for TimeSpan, issue setting SerializedProperty longValue

Viewed 417

Custom PropertyDrawer for TimeSpan, issue setting SerializedProperty longValue I've followed all the resources I can find, but no matter what I do my SerializedProperty doesn't seem to take the value.

UTimeSpan.cs:

[System.Serializable]
 public class UTimeSpan
 {
     public UTimeSpan() { }

         public UTimeSpan(double ticks)
         {
             Ticks = ticks;
         }

         [SerializeField]
         public long Ticks;

         private TimeSpan timeSpan;

         public static implicit operator TimeSpan(UTimeSpan uts)
             => uts.timeSpan;

         public static implicit operator UTimeSpan(TimeSpan ts)
             => new UTimeSpan(ts.Ticks);
     }

TimeSpanPropertyDrawer.cs:

[CustomPropertyDrawer(typeof(UTimeSpan))]
     public class TimeSpawnPropertyDrawer : PropertyDrawer
     {
         public override void OnGUI(UnityEngine.Rect position, SerializedProperty property, UnityEngine.GUIContent label)
         {
             EditorGUI.BeginProperty(position, label, property);

             position = EditorGUI.PrefixLabel(position, label);
             SerializedProperty ticks = property.FindPropertyRelative("Ticks");

             TimeSpan ts = new TimeSpan(ticks.longValue);
             int days = (int)ts.TotalDays;
             days = EditorGUI.IntField(new Rect(
                 position.x, position.y,
                 50, position.height
             ), days);

             ts = new TimeSpan(days, 0, 0);
             ticks.serializedObject.Update();
             ticks.longValue = ts.Ticks;
             ticks.serializedObject.ApplyModifiedProperties();

             EditorGUI.LabelField(new Rect(
                 position.x + 110, position.y,
                 100, position.height
             ), ts.ToString());

             EditorGUI.EndProperty();
         }
     }

But Ticks is always 0. I was under the impression that the following steps were all that's needed to manually set a SerializedProperty:

  1. serializedObject.Update()
  2. property.typeValue = value;
  3. serializedObject.ApplyModifiedProperties()

Am I missing something here? Thanks in advance!

1 Answers

This is not serialization issue but a typo.

ts = new TimeSpan(days, 0, 0, 0);

PS: UTimeSpan should be a struct as it is super simple (and rightly so). Also, timeSpan, can be just a property (TimeSpan timeSpan => new TimeSpan( this.Ticks );) or (even better) become inlined into existing operators.

Related