Unity3D [Attributes] 可视化参数使用说明整理

Unity3D 可视化参数使用说明整理     Unity3D 官方文档链接
 

 


AddComponentMenu

Description

The AddComponentMenu attribute allows you to place a script anywhere in the "Component" menu, instead of just the "Component->Scripts" menu.

You use this to organize the Component menu better, this way improving workflow when adding scripts. Important notice: You need to restart.

using UnityEngine;

[AddComponentMenu("Transform/Follow Transform")]
public class FollowTransform : MonoBehaviour
{
}

Properties

componentOrderThe order of the component in the component menu (lower is higher to the top).

Constructors

AddComponentMenuAdd an item in the Component menu.

ContextMenu

Description

The ContextMenu attribute allows you to add commands to the context menu.

In the inspector of the attached script. When the user selects the context menu, the function will be executed.

This is most useful for automatically setting up Scene data from the script. The function has to be non-static.

using UnityEngine;

public class ContextTesting : MonoBehaviour
{
    /// Add a context menu named "Do Something" in the inspector
    /// of the attached script.
    [ContextMenu("Do Something")]
    void DoSomething()
    {
        Debug.Log("Perform operation");
    }
}

Constructors

ContextMenu

 

Adds the function to the context menu of the component.

 

 


ContextMenuItemAttribute

Description

Use this attribute to add a context menu to a field that calls a named method.

using UnityEngine;

public class Example : MonoBehaviour
{
    [ContextMenuItem("Reset", "ResetBiography")]
    [Multiline(8)]
    string playerBiography = "";

    void ResetBiography()
    {
        playerBiography = "";
    }
}

Properties

functionThe name of the function that should be called.
nameThe name of the context menu item.

Constructors

ContextMenuItemAttributeUse this attribute to add a context menu to a field that calls a named method.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 

 


ExecuteAlways

Description

Makes instances of a script always execute, both as part of Play Mode and when editing.

By default, MonoBehaviours are only executed in Play Mode and only if they are on GameObjects in the main stage containing the user Scenes. They do not execute in Edit Mode, nor do they execute on objects edited in Prefab Mode, even while in Play Mode. By adding this attribute, any instance of the MonoBehaviour will have its callback functions executed at all times.

The [ExecuteAlways] attribute can be used when you want your script to perform certain things as part of Editor tooling, which is not necessarily related to the Play logic that happens in buildt Players and in Play Mode. Sometimes the Play functionality of such a script is identical to its Edit Mode functionality, while other times they differ greatly.

A MonoBehaviour using this attribute must ensure that they do not run Play logic that incorrectly modifies the object while in Edit Mode, or if the object is not part of the playing world. This can be done via Application.IsPlaying in which the script can pass in its own GameObject to check if it's part of the playing world.

If a MonoBehaviour runs Play logic in Play Mode and fails to check if its GameObject is part of the playing world, a Prefab being edited in Prefab Mode may incorrectly get modified and saved by logic intended only to be run as part of the game.

If your script makes use of static variables or Singleton patterns, you should ensure that instances of the script that belong to the playing world and instances that don't will not accidentally affect each other through those variables or Singletons.

On an object which is not part of the playing world, the functions are not called constantly like they otherwise are.
Update is only called when something in the Scene changed.
OnGUI is called when the Game view receives a non-editor-only Event that it does not use (e.g., EventType.ScrollWheel) and does not forward to the Editor's keyboard shortcut system (e.g., EventType.KeyDownEventType.KeyUp). Events forwarded to the Game view are enqueued and are not guaranteed to be processed immediately.
OnRenderObject and the other rendering callback functions are called on every repaint of the Scene view or Game view.

See Also: Application.IsPlayingrunInEditModeEditorApplication.QueuePlayerLoopUpdate.

using UnityEngine;

[ExecuteAlways]
public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        if (Application.IsPlaying(gameObject))
        {
            // Play logic
        }
        else
        {
            // Editor logic
        }
    }
}

 


ExecuteInEditMode

Description

Makes all instances of a script execute in Edit Mode.

By default, MonoBehaviours are only executed in Play Mode. By adding this attribute, any instance of the MonoBehaviour will have its callback functions executed while the Editor is in Edit Mode too.

This attribute is being phased out since it does not take Prefab Mode into account. If a Prefab with a MonoBehaviour with this attribute on is edited in Prefab Mode, and Play Mode is entered, the Editor will exit Prefab Mode to prevent accidental modifications to the Prefab caused by logic intended for Play Mode only.

To indicate that a MonoBehaviour correctly takes Prefab Mode into account and is safe to have open in Prefab Mode while in Play Mode, the attribute ExecuteAlways can be used instead of the attribute here.

The functions are not called constantly like they are in Play Mode.
Update is only called when something in the Scene changed.
OnGUI is called when the Game View receives a non-editor-only Event that it does not use (e.g., EventType.ScrollWheel) and does not forward to the Editor's keyboard shortcut system (e.g., EventType.KeyDownEventType.KeyUp). Events forwarded to the Game View are enqueued and are not guaranteed to be processed immediately.
OnRenderObject and the other rendering callback functions are called on every repaint of the Scene View or Game View.

See Also: ExecuteAlwaysApplication.IsPlayingrunInEditModeEditorApplication.QueuePlayerLoopUpdate.

// The PrintAwake script is placed on a GameObject.  The Awake function is
// called when the GameObject is started at runtime.  The script is also
// called by the Editor.  An example is when the Scene is changed to a
// different Scene in the Project window.
// The Update() function is called, for example, when the GameObject transform
// position is changed in the Editor.

using UnityEngine;

[ExecuteInEditMode]
public class PrintAwake : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Editor causes this Awake");
    }

    void Update()
    {
        Debug.Log("Editor causes this Update");
    }
}

 


HeaderAttribute

Description

Use this PropertyAttribute to add a header above some fields in the Inspector.

The header is done using a DecoratorDrawer.

using UnityEngine;

public class Example : MonoBehaviour
{
    [Header("Health Settings")]
    public int health = 0;
    public int maxHealth = 100;

    [Header("Shield Settings")]
    public int shield = 0;
    public int maxShield = 0;
}

Properties

headerThe header text.

Constructors

HeaderAttributeAdd a header above some fields in the Inspector.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


HelpURLAttribute

Description

Provide a custom documentation URL for a class.

using UnityEngine;
using UnityEditor;

[HelpURL("http://example.com/docs/MyComponent.html")]
public class MyComponent
{
}

Properties

URLThe documentation URL specified for this class.

Constructors

HelpURLAttributeInitialize the HelpURL attribute with a documentation url.

 


HideInInspector

Description

Makes a variable not show up in the inspector but be serialized.

using UnityEngine;

public class Example : MonoBehaviour
{
    // Make the variable p not show up in the inspector
    // but be serialized.
    [HideInInspector]
    int p = 5;
}

 


MinAttribute

Description

Attribute used to make a float or int variable in a script be restricted to a specific minimum value.

Properties

minThe minimum allowed value.

Constructors

MinAttributeAttribute used to make a float or int variable in a script be restricted to a specific minimum value.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


MultilineAttribute

Description

Attribute to make a string be edited with a multi-line textfield.

Constructors

MultilineAttributeAttribute used to make a string value be shown in a multiline textarea.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


PreferBinarySerialization

Description

Prefer ScriptableObject derived type to use binary serialization regardless of project's asset serialization mode.

This is useful for custom asset types that contain large amounts of data. Always keeping them stored as binary can both improve read/write performance, as well as produce more compact representations on disk. The major downsides are that binary asset files are no longer humanly readable, and that you can no longer merge them in your revision control software.

Asset serialization in Unity always uses a consistent serialization mode throughout the entirety of each file. As a result, when an asset file contains multiple assets, it might not always be possible to respect the desire to force a specific asset to use binary serialization. The serialization mode of an asset file is controlled by the main asset at that path. As a result, care has to be taken when composing complex assets using AssetDabase.CreateAsset and AssetDatabase.AddObjectToAsset to ensure that the main asset is the object with this attribute set. Scene files always follow the asset serialization mode configured in the project, thus PreferBinarySerialization is always ignored for assets embedded in Scenes.

The attribute can only be applied to ScriptableObject derived classes, it will be ignored for all other types.

using UnityEngine;

// Custom asset type that prefers binary serialization.
//
// Create a new asset file by going to "Asset/Create/Custom Data".
// If you open this new asset in a text editor, you can see how it
// is not affected by changing the project asset serialization mode.
//
[CreateAssetMenu]
[PreferBinarySerialization]
public class CustomData : ScriptableObject
{
    public float[] lotsOfFloatData = new[] { 1f, 2f, 3f };
    public byte[] lotsOfByteData = new byte[] { 4, 5, 6 };
}

 


PropertyAttribute

Description

Base class to derive custom property attributes from. Use this to create custom attributes for script variables.

A custom attributes can be hooked up with a custom PropertyDrawer class to control how a script variable with that attribute is shown in the Inspector.

See Also: PropertyDrawer class.

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


RangeAttribute

Description

Attribute used to make a float or int variable in a script be restricted to a specific range.

When this attribute is used, the float or int will be shown as a slider in the Inspector instead of the default number field.

Constructors

RangeAttributeAttribute used to make a float or int variable in a script be restricted to a specific range.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


RequireComponent

Description

The RequireComponent attribute automatically adds required components as dependencies.

When you add a script which uses RequireComponent to a GameObject, the required component will automatically be added to the GameObject. This is useful to avoid setup errors. For example a script might require that a Rigidbody is always added to the same GameObject. Using RequireComponent this will be done automatically, thus you can never get the setup wrong. Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies automatically added.

using UnityEngine;

// PlayerScript requires the GameObject to have a Rigidbody component
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.AddForce(Vector3.up);
    }
}

Constructors

RequireComponentRequire a single component.

 


RuntimeInitializeOnLoadMethodAttribute

Description

Allow a runtime class method to be initialized when a game is loaded at runtime without action from the user.

Methods marked [RuntimeInitializeOnLoadMethod] are invoked after the game has been loaded. This is after the Awake method has been invoked.

Note: The execution order of methods marked [RuntimeInitializeOnLoadMethod] is not guaranteed.

// Create a non-MonoBehaviour class which displays
// messages when a game is loaded.
using UnityEngine;

class MyClass
{
    [RuntimeInitializeOnLoadMethod]
    static void OnRuntimeMethodLoad()
    {
        Debug.Log("After Scene is loaded and game is running");
    }

    [RuntimeInitializeOnLoadMethod]
    static void OnSecondRuntimeMethodLoad()
    {
        Debug.Log("SecondMethod After Scene is loaded and game is running.");
    }
}

 

Properties

loadTypeSet RuntimeInitializeOnLoadMethod type.

Constructors

RuntimeInitializeOnLoadMethodAttributeCreation of the runtime class used when Scenes are loaded.

 


SerializeField

Description

Force Unity to serialize a private field.

When Unity serializes your scripts, it will only serialize public fields. If in addition to that you also want Unity to serialize one of your private fields you can add the SerializeField attribute to the field.

Unity will serialize all your script components, reload the new assemblies, and recreate your script components from the serialized verions. This serialization does not happen with .NET's serialization functionality, but with an internal Unity one.

The serialization system used can do the following:

- CAN serialize public nonstatic fields (of serializable types)
- CAN serialize nonpublic nonstatic fields marked with the SerializeField attribute.
- CANNOT serialize static fields.
- CANNOT serialize properties.


Your field will only serialize if it is of a type that Unity can serialize:

Serializable types are:

- All classes inheriting from UnityEngine.Object, for example GameObject, Component, MonoBehaviour, Texture2D, AnimationClip.
- All basic data types like int, string, float, bool.
- Some built-in types like Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color, Rect, LayerMask.
- Arrays of a serializable type
- List of a serializable type)
- Enums
- Structs

Note: if you put one element in a list (or array) twice, when the list gets serialized, you'll get two copies of that element, instead of one copy being in the new list twice.

Hint: Unity won't serialize Dictionary, however you could store a List<> for keys and a List<> for values, and sew them up in a non serialized dictionary on Awake(). This doesn't solve the problem of when you want to modify the dictionary and have it "saved" back, but it is a handy trick in a lot of other cases.

using UnityEngine;

public class SomePerson : MonoBehaviour
{
    //This field gets serialized because it is public.
    public string firstName = "John";

    //This field does not get serialized because it is private.
    private int age = 40;

    //This field gets serialized even though it is private
    //because it has the SerializeField attribute applied.
    [SerializeField]
    private bool hasHealthPotion = true;

    void Start()
    {
        if (hasHealthPotion)
            Debug.Log("Person's first name: " + firstName + " Person's age: " + age);
    }
}

 


SharedBetweenAnimatorsAttribute

Description

SharedBetweenAnimatorsAttribute is 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.

It's up to the programmer to choose which StateMachineBehaviour could use this attribute. Be aware that if your StateMachineBehaviour change some member variable it will affect all other Animator instance using it. See Also: StateMachineBehaviour class.

using UnityEngine;

[SharedBetweenAnimators]
public class AttackBehaviour : StateMachineBehaviour
{
    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        Debug.Log("OnStateEnter");
    }
}

 


SpaceAttribute

Description

Use this PropertyAttribute to add some spacing in the Inspector.

The spacing is done using a DecoratorDrawer.

using UnityEngine;

public class Example : MonoBehaviour
{
    int health = 0;
    int maxHealth = 100;

    [Space(10)] // 10 pixels of spacing here.

    int shield = 0;
    int maxShield = 0;
}

Properties

heightThe spacing in pixels.

Constructors

SpaceAttributeUse this DecoratorDrawer to add some spacing in the Inspector.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


TextAreaAttribute

Description

Attribute to make a string be edited with a height-flexible and scrollable text area.

You can specify the minimum and maximum lines for the TextArea, and the field will expand according to the size of the text. A scrollbar will appear if the text is bigger than the area available.

Note: The maximum lines refers to the maximum size of the TextArea. There is no maximum to the number of lines entered by the user.


Text Area in Inspector.

using UnityEngine;

public class TextAreaExample : MonoBehaviour
{
    [TextArea]
    public string MyTextArea;
}

Properties

maxLinesThe maximum amount of lines the text area can show before it starts using a scrollbar.
minLinesThe minimum amount of lines the text area will use.

Constructors

TextAreaAttributeAttribute to make a string be edited with a height-flexible and scrollable text area.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


TooltipAttribute

Description

Specify a tooltip for a field in the Inspector window.


Tooltip hovering over the class it was added to.

In the following script a Tooltip is added. This provides information to the user about the range of values for the health variable. The suggested range is provided in the TooltipAttribute string.

using UnityEngine;

public class Example : MonoBehaviour
{
    [Tooltip("Health value between 0 and 100.")]
    int health = 0;
}

Properties

tooltipThe tooltip text.

Constructors

TooltipAttributeSpecify a tooltip for a field.

Inherited Members

Properties

orderOptional field to specify the order that multiple DecorationDrawers should be drawn in.

 


UnityAPICompatibilityVersionAttribute

Description

Declares an assembly to be compatible (API wise) with a specific Unity API. Used by internal tools to avoid processing the assembly in order to decide whether assemblies may be using old Unity API.

Properties

versionVersion of Unity API.

Constructors

UnityAPICompatibilityVersionAttributeInitializes a new instance of UnityAPICompatibilityVersionAttribute.

 

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用R中的一些生物信息学包来可细菌蛋白质序列。以下是一个简单的示例: 1. 首先,你需要从NCBI网站下载你感兴趣的细菌蛋白质序列的FASTA文件。 2. 通过Biostrings包将FASTA文件读入R中。 ```R library(Biostrings) protein_seq <- readDNAStringSet("protein.fasta") ``` 3. 使用ggplot2包创建一个基本的序列图,并使用Biostrings包中的AAString函数将氨基酸序列转换为字符向量。 ```R library(ggplot2) library(dplyr) protein_df <- data.frame(seq = AAString(protein_seq)) protein_df <- protein_df %>% mutate(pos = row_number()) ggplot(protein_df, aes(x = pos, y = 1, label = seq)) + geom_text(size = 6, family = "mono") + theme_void() ``` 4. 如果你想添加一些注释,如保守性和功能域信息,可以使用biomaRt和PFAM包来获取相关数据,并将其添加到序列图中。 ```R library(biomaRt) library(PFAM) mart <- useMart("ensembl", dataset = "bacteria") protein_info <- getBM( attributes = c("start_position", "end_position", "strand", "gene_biotype"), filters = "ensembl_peptide_id", values = names(protein_seq), mart = mart ) pfam_df <- search_pfam(protein_seq) protein_df <- protein_df %>% left_join(protein_info, by = c("pos" = "start_position")) %>% left_join(pfam_df, by = c("pos" = "start")) ggplot(protein_df, aes(x = pos, y = 1, label = seq)) + geom_text( aes(color = ifelse(!is.na(pfam_id), pfam_id, "NA")), size = 6, family = "mono" ) + scale_color_brewer(palette = "Set1") + theme_void() ``` 这个示例只是一个简单的开始,你可以使用其他包和自定义代码来创建更复杂的细菌蛋白质序列可

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值