0% found this document useful (0 votes)
39 views23 pages

Unity Attributes12312

Attributes in Unity provide additional metadata that can modify properties, methods, and classes. Some key attributes include HideInInspector to hide properties, Range to limit numeric values, Tooltip for hover text, SerializeField to serialize private fields, and ImageEffectAllowedInSceneView to allow image effects in the scene view. Attributes allow extensive customization and control of how code behaves and appears in the Unity editor and runtime.

Uploaded by

Ali MENTEŞE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views23 pages

Unity Attributes12312

Attributes in Unity provide additional metadata that can modify properties, methods, and classes. Some key attributes include HideInInspector to hide properties, Range to limit numeric values, Tooltip for hover text, SerializeField to serialize private fields, and ImageEffectAllowedInSceneView to allow image effects in the scene view. Attributes allow extensive customization and control of how code behaves and appears in the Unity editor and runtime.

Uploaded by

Ali MENTEŞE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unity Attributes

Attributes are markers that can be placed above a class, property or


function in a script to indicate special behaviour.
Property Inspector
● HideInInspector: Stops the property from showing up in the inspector.
Syntax:
[HideInInspector] public bool reset = false;

● Range: Limit the range of a float or int.


Syntax:
[Range(0, 100)] public float speed = 2f;

● Min: Limit minimum value of float or int.


Syntax:
[Min(1.0f)] public float speed = 2.0;
Property Inspector

● Multiline: Show more than one lines.


Syntax:
[Multiline(4)] public string description = "";

● TextArea: Draw a flexible scrollable text area.


Syntax:
[TextArea] public string description = "";

● ColorUsage: Allow alpha channel to be modified, and allow HDR mode.


Syntax:
[ColorUsage(true, true)] public Color color = Color.white;
Property Inspector

● GradientUsage: Use on a gradient to configure the GradientField.


Syntax:
[GradientUsage(true)] public Gradient gradient;

● Space: Add space between inspector elements.


Syntax:
public float item1 = 0f;
[Space(10)]
public float item2 = 0f;

● Header: Shows a bold label in the inspector.


[Header("Stats")]public int health = 100;
Property Inspector
● Tooltip: Text shown on mouse over.
Syntax:
[Tooltip("The games score.")] public int score = 0;

● Inspector Name: Use on enum to change it's display name.


Syntax:
public enum ModelImporter Index Format
{
Auto = 0,
[InspectorName("16 bits")]
UInt16 = 1,
[InspectorName("32 bits")]
UInt32 = 2,
}

● Delayed: Use on float, int, or string to delay property being changed until user presses enter or focus changes.
Syntax:
[Delayed] public string health = 100;
Component Related
● DisallowMultipleComponent: Prevent more than 1 of this component being on a GameObject.
Syntax:
[DisallowMultipleComponent]
public class MyScript : MonoBehaviour
{
}

● RequireComponent: Tell GameObject to add this component if it isn't already added.


Syntax:
[RequireComponent(typeof(RigidBody))]
[RequireComponent(typeof(Component 1), typeof(Component2), typeof(Component 3))] // You can
enter multiple components into attribute.
public class MyClass : MonoBehaviour
{
}
Component Related

● ExecuteInEditMode: Will call MonoBehaviour methods like Update and OnEnable while in
Edit Mode.
Syntax:
[ExecuteInEditMode]
public class MyClass : MonoBehaviour
{
}

● ContextMenu: Add a context menu to a MonoBehaviour or ScriptableObject.


[ContextMenu("Reset Score")]
public void ResetScore()
{
score = 100;
}
Component Related
● ContextMenuItem: Calls a method for a field.
Syntax:
[ContextMenuItem("Reset Score", "ResetScore")]
var score = 10;
void ResetScore()
{
score = 0;
}

● SelectionBase: Will select this GameObject when a sub object is selected in the editor.
Syntax:
[SelectionBase]
public class MyClass : MonoBehaviour
{

}
Component Related

● HelpURL: Will set a custom documentation URL for this component accesible
via the help icon from the component view in the Inspector window within the
Unity Editor.
[HelpURL("https://example.com/docs/MyComponent")]

public class MyComponent : MonoBehaviour

}
Serialization
● SerializeField: Force Unity to serialize a private field.
Syntax:
[SerializeField] private int score;

● [SerializeField] private int score;


Syntax:
[NonSerialized] public int score;

● FormerlySerializedAs: If you changed the name of a serialized property, you


can set this to the old name, so save data will still work.
Syntax:
[FormerlySerializedAs("myValue")] private string m_MyValue;
Serialization
Serializable: Make a class Serializable so it will be visible in the inspector.
Syntax:
[System.Serializable]
public class MyClass
{
public int myInt = 10;
public Color myColor = Color.white;
}
Image Effect
● ImageEffectTransformsToLDR: Use on image effect to cause destination
buffer to be LDR buffer.
● ImageEffectAfterScale: "Any Image Effect with this attribute will be rendered
after Dynamic Resolution stage."
● ImageEffectAllowedInSceneView: Allows image effect to work on scene view
camera.
Syntax:
[ExecuteInEditMode, ImageEffectAllowedInSceneView]
public class BloomEffect : MonoBehaviour
{
}
Image Effect
● ImageEffectOpaque: "Any Image Effect with this attribute will be rendered after opaque geometry but
before transparent geometry."
Syntax:
[ImageEffectOpaque]
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
}

● ImageEffectUsesCommandBuffer: "Use this attribute when image effects are implemented using
Command Buffers."
Syntax:
void OnRenderImage(RenderTexture source, RenderTexture destination)
{

}
Other
● RuntimeInitializeOnLoadMethod: Calls a method once before or after the first scene has loaded.
Good for initializing Singletons without having to place objects in the scene.
Syntax:
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void OnLoad()
{
Debug.Log("Create Singletons");
}

● CreateAssetMenu: Add an option to Assets/Create for creating a ScriptableObject.


Syntax:
[CreateAssetMenu(menuName = "My ScriptableObject", order = 100)]
public class MyScriptableObject : ScriptableObject
{

}
Other
● Preserve: Preserves a members name when converting to bytecode. Useful if referencing members
through reflection.
Syntax:
[Preserve]
static void Boink()
{
Debug.Log("Boink");
}

● CustomGridBrush: "define the class as a grid brush and to make it available in the palette window."
[CustomGridBrush(true, true, true, "Default Brush")]
public class MyBrush : GridBrush
{

}
Other
● BeforeRenderOrder: "Use this BeforeRenderOrderAttribute when you need to
specify a custom callback order for Application.onBeforeRender."

● SharedBetweenAnimators: "...an attribute that specify that this


StateMachineBehaviour should be instantiate only once and shared among all
Animator instance. This attribute reduce the memory footprint for each controller
instance."
Syntax:
[SharedBetweenAnimatorsAttribute]
public class AttackBehavior : StateMachineBehaviour
{
}
Other
● AssemblyIsEditorAssembly: Can use this rather than place the script in an "Editor" folder.
Syntax:
[assembly:AssemblyIsEditorAssembly]
public class MyEditorClass : MonoBehaviour
{
}

● ExcludeFromPreset: "Add this attribute to a class to prevent creating a Preset from the instances of
the class."
Syntax:
[ExcludeFromPreset]
public class MyClass : MonoBehaviour
{
public int score = 10; // Won't be used in Preset?
}
Other
● ExcludeFromObjectFactory: "Add this attribute to a class to prevent the class
and its inherited classes from being created with ObjectFactory methods."

● ExcludeFromCoverage: "Allows you to exclude an Assembly, Class,


Constructor, Method or Struct from Coverage."
Undocumented
● DefaultExecutionOrder: Probably sets the Script Execution order.
Syntax:
[DefaultExecutionOrder(100)]
public class MyScript : MonoBehaviour
{
}

● RejectDragAndDropMaterial: Probably prevents materials being applied through dragging


and dropping in the editor.
[RejectDragAndDropMaterial]
public class MyRenderer : MonoBehaviour
{
}
Editor
● MenuItem: Adds a menu to the Editor toolbar.
Syntax:
[MenuItem("MyMenu/Do Something")]
static void DoSomething()
{
Debug.Log("Doing Something...");
}

● InitializeOnLoadMethod: Called after scripts have been compiled.


Syntax:
[InitializeOnLoadMethod]
static void OnProjectLoadedInEditor()
{
Debug.Log("Project loaded in Unity Editor");
}
Editor
● DidReloadScripts: Called after scripts have reloaded. Can take an order parameter. Methods with lower orders are called earlier.
Syntax:
using UnityEditor.Callbacks;
[DidReloadScripts(100)]
static void OnScriptsReloaded()
{
Debug.Log("Reloaded.");
}

● OnOpenAsset: Called when double clicking an asset in the project browser.


Syntax:
using UnityEditor.Callbacks;
[OnOpenAssetAttribute(1)]
static bool step1(int instanceID, int line)
{
string name = EditorUtility.InstanceIDToObject(instanceID).name;
Debug.Log("Open Asset step: 1 (" + name + ")");
return false; // we did not handle the open
}
Editor
● PostProcessBuild: Called after game has been built.
Syntax:
using UnityEditor.Callbacks;

[PostProcessBuildAttribute(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
}

● PostProcessScene: Called after scene has been built.


using UnityEditor.Callbacks;
[PostProcessSceneAttribute (2)]
public static void OnPostprocessScene()
{
}
Thank You

You might also like