How to make decimal variables visible in Inspector?

I want to change a decimal variables in runtime in the inspector or just watch it without using

Debug.Log(variable);

Is this anyhow possible?

Like dns said, Unity can’t serialize the decimal type on it’s own. If you want Unity to actually “store” (serialize) the value, you have to provide your own way to serialize the value. This wrapper class does this:

//SerializableDecimal.cs
using UnityEngine;
using System.Collections;

[System.Serializable]
public class SerializableDecimal : ISerializationCallbackReceiver
{
	public decimal value;
	[SerializeField]
	private int[] data;

	public void OnBeforeSerialize ()
	{
		data = decimal.GetBits(value);
	}
	public void OnAfterDeserialize ()
	{
		if (data != null && data.Length == 4)
		{
			value = new decimal(data);
		}
	}
}

The field “value” is what you would use at runtime. Whenever Unity wants to serialize this custom class, it first copies the 4 internal uint fields into fields that unity can serialize. Now Unity will store those 4 values which made up a decimal value. When deserializing it restores those values.

Of course the inspector can only “show” serialized data, so it will show by default the data array with the 4 internal fields (hi, mid, lo and flags) which are difficult to edit. To get a visual representation you have to provide a PropertyDrawer like this:

//SerializableDecimalDrawer.cs
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(SerializableDecimal))]
public class SerializableDecimalDrawer : PropertyDrawer
{
	public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
	{
		var obj = property.serializedObject.targetObject;
		var inst = (SerializableDecimal)this.fieldInfo.GetValue(obj);
		var fieldRect = EditorGUI.PrefixLabel(position, label);
		string text = GUI.TextField(fieldRect, inst.value.ToString());
		if (GUI.changed)
		{
			decimal val;
			if(decimal.TryParse(text, out val))
			{
				inst.value = val;
				property.serializedObject.ApplyModifiedProperties();
			}
		}
	}
}

With those two classes you have a decimal type that is serialized and can be edited / viewed in the inspector.

Keep in mind that the PropertyDrawer class need to be inside an “/Editor/” folder since it’s an editor class.

edit
Just noticed that i probably should also give a usage example :wink: Here it is:

public class DecimalTestScript : MonoBehaviour
{
	public SerializableDecimal val;
	void Start ()
	{
		Debug.Log("Val: " + val.value);
	}
}

So the only difference from using a “normal” decimal value is, that you have to use:

    val.value

instead of

    val

Of course you can implement implicit and explicit cast operators to use a SerializableDecimal just like a decimal, but such operators don’t work in all cases.

It does not work if I use SerializableDecimal class within a ScriptableObject inherited class =(