Unity 之 Scripts

1.携程也可以通过关闭它所在的物体来停止,SetActive(false),或者调用Destroy(example)(其中example是一个MonoBehaviour实例)会立即触发OnDisable并处理协程,从而有效地阻止它,调用enable不会停止协程

2.也可以通过声明命名空间来定义不同的属性

3.属性,属性分为editor属性和engine属性

 engine 属性:

AddComponentMenu

AddComponentMenu属性允许您将脚本放置在“组件”菜单中的任何位置,而不仅仅是“组件->脚本”菜单。

using UnityEngine;

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

AssemblyIsEditorAssembly

程序集中任何含有此属性的类,都被当作是编辑器类

AssemblyIsEditorAssembly Constructor.

BeforeRenderOrder  Attribute

在 调用 Application.onBeforeRender 事件时,根据添加了该属性的order来确定方法直行的顺序,从低到高执行,如果没加该属性,默认order是0

ColorUsage  Attribute

为颜色增加一个颜色选择器,有两个参数,第一个是否显示alpha值,第二个是否显示hdr颜色

ColorUsageAttribute Attribute for Color fields. Used for configuring the GUI for the color.

ContextMenu

为脚本的右上角的齿轮添加一个运行方法的快捷键,对场景内配置数据比较有用

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");
    }
}

ContextMenuItemAttribute

给这个属性右键添加一个方法,即在属性面板上右击playerBiography,会出现Reset按钮,点击该按钮,执行

ResetBiography方法

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

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

CreateAssetMenu Attribute

把继承自ScriptableObject的类,创建成一个".asset"资源文件,默认在 Assets/Create/你脚本的名字 的子菜单下

Properties

fileName 新创建实例的名字
menuName 在 Assets/Create 菜单下的名字
order 在 Assets/Create menu.的顺序

ExecuteAlways

不管是在编辑器状态还是在运行状态,该脚本始终在运行

默认 MonoBehaviours 只在 Play Mode 运行,并且脚本还要挂在到游戏物体上,不会再编辑器下运行 ,或者就算挂在到Prefab Mode上也不会运行. 添加这个属性之后, 任何MonoBehaviour 都会一直执行

当您希望脚本作为编辑器工具的一部分执行某些事情时,可以使用[ExecuteAlways]属性,有时,这种脚本的播放功能与其编辑模式功能相同,而其他时候则有很大的不同。

A MonoBehaviour 要确保他当中没有编写游戏逻辑,只是在编辑器模式下运行 ,否则可能会造成错误. 可以通过Application.IsPlaying来确定游戏是否在运行状态

using UnityEngine;

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

ExecuteInEditMode

让脚本在编辑器状态下也能运行

using UnityEngine;

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

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

GradientUsage Attribute

返回一个颜色的渐变编辑器,参数是是否打开HDR

HeaderAttribute

添加一个标头,使用 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;
}

 

HelpURLAttribute

class in UnityEngine

/

Implemented in:UnityEngine.CoreModule

Leave feedback

Description

为一个类提供一个方法说明,按住CTRL键可转到连接,点击下面的图表就会转到说明

using UnityEngine;
using UnityEditor;

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

HideInInspector

属性在属性面板上隐藏

using UnityEngine;

public class Example : MonoBehaviour
{  
    [HideInInspector]
    public int p = 5;
}

ImageEffectAfterScale

 

添加这个属性的图片,会在Dynamic Resolution stage.之后渲染

如果您希望在动态分辨率缩小后应用图像效果,请添加此属性。效果将以全分辨率呈现,这对于在某种程度上依赖于屏幕宽度和高度的特定大小的效果非常重要。没看出来啥效果,可能就是分辨率变小了,图片的分辨率并不会改变,这样更清晰

ImageEffectAllowedInSceneView

在 Scene view camera.之后渲染

ImageEffectOpaque

 

图片将在透明和非透明之间物体渲染 opaque geometry but before transparent geometry.

这允许广泛使用深度缓冲(SSAO等)来影响不透明像素的效果。此属性可用于减少具有后期处理的场景中的可视工件数量

InspectorNameAttribute

 

使用这个属性改变在属性面板中的名字,但是要加在枚举类型上

using UnityEngine;

public enum ModelImporterIndexFormat
{
    Auto = 0,
    [InspectorName("16 bits")]
    UInt16 = 1,
    [InspectorName("32 bits")]
    UInt32 = 2,
}

MinAttribute

 

限定一个float或者int类型的最小值

MultilineAttribute

 

声明一个可以多行编辑的字符串

RangeAttribute

 

给 float or int 变量一个范围,用slider表示

RequireComponent

 RequireComponent 会自动添加需要的组件

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);
    }
}

RuntimeInitializeOnLoadMethodAttribute

在场景加载之后,运行该类的静态方法

标记有 [RuntimeInitializeOnLoadMethod]在加载场景之后,在awake调用之后执行

Note: 但是互标有[RuntimeInitializeOnLoadMethod]的方法的执行顺序,不确定

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.");
    }
}

SelectionBaseAttribute

把这个属性添加到一个类上面,并把该脚本添加到一个物体上面,当你在场景中选中该物体的子物体时,会快速定位到它身上,就比如你点击一个prefab的子物体,它会自动定位到根节点一样,单击一次,会定位到挂有该脚本的物体,单击两次会定位到你点击的物体

SerializeField

强制Unity序列化一个私有字段

当Unity序列化你的脚本时,它只序列化公共字段. 如果你也想要Unity序列化你的私有字段,你可以添加SerializeField属性到那些字段。
Unity序列化所有的脚本组件,重新加载新的程序集,并从序列化的版本中重新创建脚本组件。这种序列化是通过一个内部的Unity序列化系统完成的;而不是.net的序列化功能。


序列化系统可以做到以下几点:

- 可以序列化public  非静态字段或者serializable 类型
-可以通过 SerializeField属性序列化私有的非静态类型
- 不能序列化静态字段,这也就是为何静态字段不能在属性面板上显示出来的原因,不管是不是共有的或私有的
-不能序列化属性

Serializable types


Unity可以序列化以下类型的字段

- 继承自 UnityEngine.Object类的类型,比如 for example GameObject, Component, MonoBehaviour, Texture2D, AnimationClip.
- 所有基础类型, such as int, string, float, bool.
- 一些内置类型, such as Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color, Rect, LayerMask.
- serializable type类型的数组
- serializable type类型的列表
- Enums 枚举
- Structs 结构体

For more information on serialization, see Script Serialization.

Note: I如果您将一个元素放入一个列表(或数组)两次,当列表被序列化时,您将得到该元素的两个副本,而不是一个副本在新列表中出现两次

Note:如果你想要序列化自定义的结构体Struct field, 需要给结构体加上 [System.Serializable]属性

Hint: Unity 不能序列化字典 Dictionary,但是你可以通过两个list分别存储keys和valus,然后再on Awake()里面把他们存储到字典里面 ,他没有解决什么时候需要修改字典并将其“保存”回来的问题,但是在许多其他情况下这是一个方便的技巧。

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

SharedBetweenAnimatorsAttribute 指定StateMachineBehaviour应该只实例化一次并在所有Animator实例之间共享 ,此属性减少每个控制器实例的内存占用

你来决定哪个StateMachineBehaviour 使用这个属性 attribute. 请注意,如果您的StateMachineBehaviour更改了某个成员变量,它将影响使用它的所有其他Animator实例. 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

使用 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;
}

TextAreaAttribute

实现一个高度可调可以滚动的字符串

你可以声明区域框显示的最小和最大的字符串的行数, minimum and maximum , 文字区域会根据文字的内容自动扩展输入框的大小,超出的部分会有一个滚动条

Note: 最大行是指文本区域显示字符串的行数。用户输入的行数没有上限。


Text Area in Inspector.

using UnityEngine;

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

TooltipAttribute

为一个属性显示一个说明,当鼠标停留在上面的时候 tooltip for a field in the Inspector window.


Tooltip hovering over the class it was added to.

using UnityEngine;

public class Example : MonoBehaviour
{
    [Tooltip("Health value between 0 and 100.")]
    int health = 0;
}
发布了80 篇原创文章 · 获赞 7 · 访问量 2704

猜你喜欢

转载自blog.csdn.net/qq_37672438/article/details/103278246