Unity C# Attributes


Attributes Used In Unity
An attribute is a declarative tag that conveys information about the behaviors of various elements like classes, methods, structures, enums etc. in the program.
An attribute is depicted by square ([ ]) brackets placed above the element it is meant for.
Attributes are used for adding metadata, such as information such as comments, description, methods and classes to a program. The .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.
Syntax for specifying an attribute:
[attribute(positional_parameters, name_parameter = value, ...)]
element
We will go over the pre-defined attributes on another post.
For now let's go over the most useful custom attributes that Unity has, as you now have a basic knowledge of what attributes are.
DisallowMultipleComponent: Prevents the same component from being added to the same game object.
[DisallowMultipleComponent]
public class PlayerControl : MonoBehaviour
{ .....
  .....
}
RequireComponnent(typeof(MonoBehavior)): Makes sure to add the specified component to the game object as well. It's useful when you always need another component on the game object in order for this component to work.
[RequireComponent(typeof(PlayerControl))]
public class PlayerNetwork : MonoBehaviour
{
  .....
  .....
}
HideInInspector: The public field tagged with this attribute will not be shown in the inspector.
.
.
[HideInInspector]
 public float teamAlign = 0.0f;
 public int ammoCount = 30;
 public string playerName;
.
.
SerializeField: Displays a field in the inspector even if it is private.
.
.
[SerializeField] private float sensitivity = 5.0f;
[SerializeField] private float smoothing = 10.0f;
[SerializeField] private float speed = 20;
.
.
Header(string): Displays a heading text on top of the element it's applied on.
.
.
[SerializeField, Header("Connection Details")] private Text connectText;
[SerializeField] private GameObject player;
[SerializeField] private GameObject lobbyCamera;
.
.
Range(float min, float max): Displays a slider with the appropriate minimum and maximum value.
.
.
[SerializeField] private float sensitivity = 5.0f;
[SerializeField] private float smoothing = 10.0f;
[SerializeField, Range(0,30)] private float speed = 20;
.
.
ToolTip(string): Shows a tool tip while mouse hovers over the element
.
.
[SerializeField, Range(0,30), Tooltip("Speed Of Player")] private float speed = 20;
private Vector2 mouseLook;
private Vector2 smoothVec;
.
.
Hope you learnt something today.😁
Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.
If you have any questions that you might have about shaders, C# or Unity development in general don't be shy and leave a message on my facebook page or down in the comments.
For more Unity tutorials, go HERE.
For More C# Tutorials, go HERE.