5 Attribute Tips – Unity Tips (Volume #2)

In this volume #2 of Unity tips, I’m gonna share with you 5 useful attributes to use in your script. (5 Editor Tips – Unity Tips (Volume #1))
Every Tuesday, Unity developers across the globe share some useful tips about Unity. Check #UnityTips to see it yourself!

#6 Require Component

Most of the times we use some components in our scripts.
You can ensure that whoever uses the script will have the components needed by using the “RequireComponent” attribute.
What does it do? It will add that component to the object instantly.

[RequireComponent(typeof(ComponentName))]

#7 Add Component Menu

You can add your script to the component menu with a custom path starting from the “Component” as the root.
Use “AddComponentMenu” attribute.

[AddComponentMenu("Path/To/Script")]

#8 Header

To make your script user-friendly in the editor, you can add headers on top of the variables using the “Header” attribute.

[Header("Title")]

#9 Range

In some cases, you want the variables to stick between two values, for example, the player’s health should be between 0 and 100.
Luckily there’s an attribute for that which is “Range”. You have to place it on top of the affected variable.
It will limit the variable and provide a slider.

[Range(0, 100)]
public float health;

#10 Context Menu

You can call a function in the editor (runtime too) and accessing it through the gear icon of the current script by using the “ContextMenu”.
Simply, pass the ContextMenu along with the title on top of the desired function to be called.

[ContextMenu("Say Hello!")]
public void Hello(){
  print("Hello!");
}

Share Your Tips!

Which one of the above is your favorite?
If you got other ones, share them in the comments below and on Twitter using #UnityTips.

Liked the post? Help us sharing it.