- Home /
Custom inspector for System class (TimeSpan)
I'm making use of System.TimeSpan in a couple of places, and I want these to be editable in the inspector. What's the best way of going about this? I tried the following but it doesn't work as UnityEngine.Object cannot be converted to System.Timespan...
[CustomEditor(typeof(TimeSpan))]
public class TimeSpanInspector : Editor
{
private TimeSpan _ts;
public void OnEnable()
{
_ts = (TimeSpan)target;
}
public override void OnInspectorGUI()
{
GUILayout.BeginHorizontal();
int hours = EditorGUILayout.IntField(_ts.Hours, GUILayout.Width(50));
GUILayout.EndHorizontal();
_ts = new TimeSpan(hours, 0, 0);
}
}
I'm also looking to do this, though I'm trying to use the CustomDrawer, as that'll make timespans show up no matter what they're in... but yeah, still not working.
Answer by Jamora · Feb 27, 2014 at 09:26 PM
The easiest way to accomplish this would be to write a MonoBehaviour wrapper for TimeSpan and then have references to that wrapper. This does impose some limitations, namely, that you need to attach your TimeSpan-wrapper to a GameObject. To inspect this object, you firstly need a custom inspector (or a propery drawer). Secondly you need to use the getters and setters in the wrapper instead of directly accessing the TimeSpan when inspecting.
For those who do not know what a wrapper is, it's basically a class that is 'wrapped' around another class, providing suitable implementations for the current platform. The TimeSpan wrapper could look something like this:
public class TimeSpanWrapper : MonoBehavior{
private TimeSpan timeSpan;
//use this to create new TimeSpanWrappers
public static TimeSpanWrapper Create(GameObject go, int hours, int minutes, int seconds){
TimeSpanWrapper tsw = go.AddComponent<TimeSpanWrapper>();
tsw.Init(hours, minutes, seconds);
return tsw;
}
public void Init(int hours, int minutes, int seconds){
timeSpan = new TimeSpan(hours, minutes, seconds);
//this is actually the constructor where we set
//the values for the private TimeSpan.
}
//Here goes methods you need from TimeSpan. If
//TimeSpan had a GetHours method, we would create a
//method as follows:
public int GetHours(){ return TimeSpan.GetHours(); }
}
Answer by ben-tmg · Feb 27, 2014 at 09:35 PM
Everything in the inspector must derive from UNityEngine.Object (that is what the error means). To get around this you'll need to create a new class that has a TimeSpan variable on it.
ie
public class UnityTimeSpan : MonoBehaviour
{
public TimeSpan span;
}
Then you'll have to use UnityTimeSpan instead of TimeSpan and you can create an editor for UnityTimeSpan.
Your answer
Follow this Question
Related Questions
Accessing local system ( File Browser ) 2 Answers
Help, getting ambiguous reference error 1 Answer
Help, getting ambiguous reference error 1 Answer
See if a time span is bigger than X 4 Answers