- Home /
Is it possible to write text inside of textboxes for editable values in the inspector?
Hello everyone, I've got a really simple question that is probably best explained by this picture:
As you can see this is an example from Bolt, but it's used in a special settings window (plus I don't have source code). I was simply wondering if this is something I could do for editable values on my game object components. I would really love to be able to specify the units of my variables, it would really help me keep things readable.
Thanks!
Answer by PartyBoat · Aug 14, 2016 at 01:41 AM
Looks like the possible solutions to this problem are way more work then I want to spend on this tiny feature. However, I did run into the TooltipAtrribute and HeaderAttribute, and I think I'll probably be using one or the other for the same purpose. It's a little less sexy, but it gets the job done in one line of code. Here is an example of usage for those interested:
[Tooltip("Units: m/s")]
public float velocity = 0f;
Edit: Here is the real answer
So I guess I was just being lazy but someone on the Unity subreddit was kind enough to post a fully working solution and it's super simple. First you have to add two scripts to your project "AdditionalTextAttribute" and "AdditionalTextDrawer". In AdditionalTextAttribute.cs put this:
using UnityEngine;
public class AdditionalTextAttribute : PropertyAttribute
{
public readonly string Text;
public AdditionalTextAttribute(string text)
{
Text = text + " ";
}
}
In AdditionalTextDrawer.cs put this:
using UnityEditor;
using UnityEngine;
/*
* Usage: simply put a Attribute in front of your variables like this:
*
* [AdditionalText("m/s")]
* public float velocity = 20f;
*
* Use at own risk for variables that are not rendered in text fields (you'll might get multiple texts over each other)
*/
[CustomPropertyDrawer(typeof(AdditionalTextAttribute))]
public class AdditionalTextDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.PropertyField(position, property, label);
var style = new GUIStyle(EditorStyles.label);
style.alignment = TextAnchor.MiddleRight;
style.normal.textColor = Color.gray;
var attrib = attribute as AdditionalTextAttribute;
GUI.Label(position, attrib.Text, style);
}
}
Then you can write code like the following anywhere in your project to get text inside of the property text field:
[AdditionalText("m/s^2")]
public float acceleration = 20f;
Looks great just like the reference image I gave! here is the github page for the original solution given to me, basically all I did was remove the namespace usage to make it even easier to throw into a project.