- Home /
What does a [SomeName] Above A Variable Mean?
I know there is [System.Serializable] put above things that are meant to show up in the inspector.
But I find a lot of plugins I use have things like this
[PrimaryKey]
public int StarShipID { get; set; }
What is the name of the thing [Whatever] called? How does one make these and define what it does?
They somehow add quality or ...attribute to a variable or class or else. They are meta data, meaning you cannot modify them as they are not part of the runtime process and belong to the manifest.
It is like the postcode of a building, you can change the building, the shape of it, who goes in and other things but an attribute would define the postcoe and you cannot modify that, only can you access it and use.
Attributes will also define the variable/class just like the postcode would define if the building is in East side, $$anonymous$$anhattan or the Bronx.
Whether you want to modify the attribute you have to rebuild the app.
There's a nice tutorial series on Attributes and Reflection in C# by Jamie $$anonymous$$ing: C# Hello World Attributes if you want to know how they work.
Hey thanks guys, this is really going to help me level up my coding with Unity. XD
Answer by Flavioli · Apr 22, 2015 at 09:45 AM
As others mentioned, those are attributes. They allow you to provide more data or functionality to classes, methods, properties, fields, etc.. Actually, if you make a custom attribute, you'll see that there isn't too much magic behind how they behave; here is a small (albeit a bit silly) example of creating a custom attribute and then using it in your own code.
Declare the silly attribute:
public class MyValueAttribute : System.Attribute
{
public int SomeValue = 0;
public MyValueAttribute(int value)
{
this.SomeValue = value;
}
}
To apply it to a class (note you do not need to call it by its full name when used in square brackets, though you can actually do so if you want):
[MyValue(5)]
public class Joystick : MonoBehaviour
{
// ... //
You can employ Reflection to actually make "use" of this silly attribute (using the word "use" loosely):
object[] attributes = typeof(Joystick).GetCustomAttributes(typeof(MyValueAttribute), false);
if (attributes.Length > 0)
{
MyValueAttribute myAttribute = attributes[0] as MyValueAttribute;
System.Diagnostics.Debug.Assert(myAttribute.SomeValue == 5);
}
As you might imagine, you can probably find a more practical way to use attributes, though I find that they are more interesting and applicable when designing frameworks than in everyday code. One of my favorite uses for attributes is when applied to enum values, which can be quite nifty in many cases.
Your answer
![](https://koobas.hobune.stream/wayback/20220613193739im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Problem with var in C# (Vector3, transform and similiar) 1 Answer