How to show script fields in the Inspector in Unity?
Just like any Unity built-in Components, you can allow values in your script to be edited from the Inspector.
Here are some examples:
public class InspectorFields : MonoBehaviour
{
public int intField=5;
public float floatField=0.5f;
public string stringField="Unity";
public bool boolField= true;
public Color colorField;
public Vector3 vector3Field;
public Gradient GradientField;
public Rect rectField;
public Quaternion QuaternionField;
public AnimationCurve animationCurve;
public Vector3[] Vector3Array;
public List<int> intList;public enum Shapes
{
rectangle,
triangle,
square,
circle
}
public Shapes EnumField;}
The result in the inspector is shown below :
Note that wherever a capital letter occurs in a variable name, Unity adds a space in the Inspector label of that variable. However, this is only for display purposes.
How to use Unity Attributes?
There are many Property Attributes in Unity that you can use to make the inspector easier to use, save you time and prevent mistakes. Using these unity attributes you can for example:
- Clamp values to acceptable ranges;
- Customize Color settings;
- Add custom actions to your inspector window.
The next table and piece of code shows you some examples of Property Attributes use cases.
Here is an example of using attributes in unity:
[Range(0, 10)]
public int score;
[Range(-5f, 5f)]
public float Health;
[Space]
[TextArea]
[Tooltip("A text Area")]
public string textarea;
[Header("Multiline Area")]
[Multiline]
public string multiline;
[SerializeField]
private bool boolField2= true;
//This one will not show in the inspector
[HideInInspector]
public double doubleField=5.9f;
[System.Serializable]
public struct Points
{
public float X;
public float Y;
public float Z;
}
public Points pointStruct;
And the result will be as shown in the next image :
Thank you for reading my article. If you like it, please share it.
See also :