2016-08-23 14:49:58 yu__jiaoshou 阅读数 1151

Unity 3D - 可视化变量标注 :

常用 :

  • 拖动条 :
    [Range(0, 100)]

  • 大标题 :
    [HeaderAttribute(“属性”)]

  • 停留提示 :
    [TooltipAttribute (“生命值”)]

  • 隐藏 :
    [HideInInspector]


public 和 private 正常情况:

  • public 的变量值会显示在 Inspector 视图中 .
public float HP;

这里写图片描述

  • private 不会显示在 Inspector 面板上 .
private float HP;

这里写图片描述


私有变量 ( private ) 显示在 Inspector 面板上 :

如何想要私有变量 (private )也显示在Inspector 面板上 , 那么就需要使用序列化 (SerializeField) .

[SerializeField]  private float HP;

这里写图片描述

使用 [SerializeField] 可以让 private 变量显示在 Inspector 面板上 , 并且不会改变变量本质( 变量任是私有的 ) .


Range 显示 :

[Range(0,100)]  private float HP;

加上一个Range 参数 , 显示方式会变成拖动条形式 .

这里写图片描述


HeaderAttribute 显示 :

 [Range(0, 100), HeaderAttribute("血量")] private float HP;

加上HeaderAttribute (“血量”) 后 , 在 Inspector 上显示如下图 .

这里写图片描述


TooltipAttribute 显示 :

[SerializeField, Range(0, 100), HeaderAttribute("血量"), TooltipAttribute("生命值")]
private float HP;

[SerializeField, Range(0, 100), HeaderAttribute("蓝量"), TooltipAttribute("魔法值")]
private float MP;

加上TooltipAttribute (“生命值”) , 鼠标放在对应变量上 , 显示如图提示 .

这里写图片描述

2019-01-24 12:36:27 WZRomance613 阅读数 167

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

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

Constructors

AddComponentMenu Add 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

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

Constructors

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

Inherited Members

Properties

order Optional 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

header The header text.

Constructors

HeaderAttribute Add a header above some fields in the Inspector.

Inherited Members

Properties

order Optional 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

URL The documentation URL specified for this class.

Constructors

HelpURLAttribute Initialize 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

min The minimum allowed value.

Constructors

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

Inherited Members

Properties

order Optional 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

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

Inherited Members

Properties

order Optional 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

order Optional 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

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

Inherited Members

Properties

order Optional 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

RequireComponent Require 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

loadType Set RuntimeInitializeOnLoadMethod type.

Constructors

RuntimeInitializeOnLoadMethodAttribute Creation 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

height The spacing in pixels.

Constructors

SpaceAttribute Use this DecoratorDrawer to add some spacing in the Inspector.

Inherited Members

Properties

order Optional 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

maxLines The maximum amount of lines the text area can show before it starts using a scrollbar.
minLines The minimum amount of lines the text area will use.

Constructors

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

Inherited Members

Properties

order Optional 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

tooltip The tooltip text.

Constructors

TooltipAttribute Specify a tooltip for a field.

Inherited Members

Properties

order Optional 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

version Version of Unity API.

Constructors

UnityAPICompatibilityVersionAttribute Initializes a new instance of UnityAPICompatibilityVersionAttribute.

 

2013-11-05 11:40:32 qn9663 阅读数 1487

      之前有一段时间在想可视化脚本做游戏的可行性.首先看了Playmaker,感觉非常强大,把脚本API封装成脚本组件,把判断语句也封装了.对调用流程用流程图显示,并且可以看到执行过程,我觉得这点上面做的非常好.看了其脚本的变量定义,其实我觉得她有一个缺点,她不能访问宿主变量,也就会吧底层完全分离.考虑到需求,觉得目前她不合适做大项目.

      后来用了uScript,发现她是通过模块(类似UML)那样的界面做好流程,然后生成脚本代码,也就意味着她的想法是通过界面生成原生脚本,这样的优点是代码执行效率高,可以随意访问宿主变量.确实变的灵活不少.试用后发现,事件多了,变量多了,她也很麻烦,比如if((a || b || c) && d)和对象引用后,她可能要很多可视化的逻辑控制器完成.结果就是可视化界面看起来盘大无比.失去了可视化的优势.


总结:

       不管是Playermaker还是后者,都有一样的问题

      1,不能做宏定义.后期移植麻烦

      2,不能做批量查找和替换,后期修改很麻烦.

      3,不能做查找,比如找到响应的事件逻辑段.

      4,对于一些不是RPG,ARPG,类型的游戏不适用.

我当初的需求其实是想有一个可视化可以图形化显示我的函数调用流程.

综合因素,我不选择可视化脚本.因为U3D已经是可视化引擎了.

2018-09-21 17:26:34 n_moling 阅读数 1143

首先感谢 FransicZhang的博客,链接:https://blog.csdn.net/fransiczhang/article/details/78093131

下面获取输入音频及处理代码主要根据FransicZhang的博客所写:

/************************************************************
  FileName: AudioVisualization.cs
  Author:末零       Version :1.0          Date: 2018-9-21
  Description:音频可视化
************************************************************/

using UnityEngine;

public class AudioVisualization : MonoBehaviour
{
    public float speed = 20f;//速度
    public float peak = 10;//峰值控制

    public float volume;
    private AudioClip micRecord;
    private string device;
    private float x;
    private void Start()
    {
        device = Microphone.devices[0];//获取设备麦克风
        micRecord = Microphone.Start(device, true, 999, 44100);
    }
    private void Update()
    {
        volume = GetMaxVolume();

        transform.Translate(Vector3.right * speed * Time.deltaTime);
        x = gameObject.transform.localPosition.x;
        //处理峰值
        if (volume > 0.9f)
        {
            volume = volume * speed * Time.deltaTime;
            gameObject.transform.localPosition = new Vector3(x, volume * peak, 0);
        }
        else
        {
            gameObject.transform.localPosition = new Vector3(x, volume * peak, 0);
        }
    }
    //每一振处理那一帧接收的音频文件
    private float GetMaxVolume()
    {
        float maxVolume = 0f;
        //剪切音频
        float[] volumeData = new float[128];
        int offset = Microphone.GetPosition(device) - 128 + 1;
        if (offset < 0)
        {
            return 0;
        }
        micRecord.GetData(volumeData, offset);

        for (int i = 0; i < 128; i++)
        {
            float tempMax = volumeData[i];//修改音量的敏感值
            if (maxVolume < tempMax)
            {
                maxVolume = tempMax;
            }
        }
        return maxVolume;
    }
}

可以把这部分代码挂到一个GameObject上,并加上拖尾组件,便可实现音频曲线,前提是获取的麦克风权限,前面博客已有涉及。处理好音频部分,接下来的任务就是把它显示在界面上。

首先,写一个摄像机跟随脚本:

/************************************************************
  FileName: CameraFollow.cs
  Author:末零       Version :1.0          Date: 2018--
  Description:摄像机跟随
************************************************************/

using UnityEngine;

public class CameraFollow: MonoBehaviour {

    public Transform target;
    private float distance = 59;

    private void OnEnable()
    {
        distance = transform.position.x - target.position.x;
    }

    private void Update () 
	{
        transform.position = new Vector3(target.position.x + distance, transform.position.y, transform.position.z);
	}
}

然后通过RenderTexture显示在UI界面上。

2018-12-10 14:10:08 qq_30058057 阅读数 95

使用unity可视化工具需要在函数**OnDrawGizms()以及OnDrawGizmsSelected()**函数中使用

两者中间的区别是:OnDrawGizmsSelected()只有在选中挂载写有此函数的脚本的物体被选中时才会绘制
而OnDrawGizms()则是只要场景中含有此函数的脚本即可绘制
例子
在坐标(0,0,0)处绘制一个红色的边长为1的cube

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    //private void OnDrawGizmos()
    //{
    //    Gizmos.color = Color.red;
    //    Gizmos.DrawCube(Vector3.zero, Vector3.one);
    //}
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawCube(Vector3.zero, Vector3.one);
    }
}

含有脚本的物体被选中时:

含有脚本的物体被选中时:

含有脚本的物体未被选中时:

含有脚本的物体未被选中时:

使用OnDrawGizms()函数则不管物体选不选中都可以绘制

Gizms内置函数:
在这里插入图片描述

没有更多推荐了,返回首页