C#程序员整理的Unity 3D笔记(十七):EasyTouch 4.X User & API documentation

What’s new in EasyTouch 4

· Unity UI integration.

UGui集成

· EasyTouchTrigger component, that allow you to call existing functions with out a line of code relative to an EasyTouch event.

EasyTouchTrigger组件,不用写一行代码就可以调用存在的方法

· New two finger gesture algorithm.

新的双手指手势算法

· The simulation of the second finger can be activated or not

第二手指模拟可以被激活或禁用

· 2 methods for two fingers auto selection Finger & Average

双手指有两个方法自动选择手指或者评价值

· The double tap is now configurable.

双击可以配置

· Gesture priority between tap & slips.

单击和滑动手势优先

· 4 new build in swipe direction UpLeft, UpRight, DownLeft , DownRight

在滑动方向上4个新设计:左上,左下,右上,右下

· Auto update picked object option

自动更新选择对象的选项

· tmpArray of touches is now cached to prevent garbage collector.

缓存中高级临时数组使用预防垃圾清理

· New inspector style

新检视面板的样式

features no longer supported

· EasyJoystick & EasyButton are no longer supported, they are replaced by Easy Touch Controls

EasyJoystick & EasyButton不在支持,被Easy Touch Controls代替。

· Reserved area are no longer supported, the new Unity UI is more flexible

保留区不在支持,新的UGUI更灵活。

· Message sending via the internal management system in Unity for javascript user has been replaced by the component EasyTouchTrigger.

Unity自带的消息机制被EasyTouchTrigger.组件代替。

What is EasyTouch

EasyTouch allow you to quickly and easily develop actions based on a touchscreen or a mouse gesture. All major gestures are recognized such as touch, tap, double tape, twist, pinch.. and much more.

EasyTouch允许您快速轻松地开发基于触摸屏或鼠标手势的行为。

EasyTouch allows automatic detection of all gameobjects with collider on layers that you can set. To allow easy handling of the various elements that make up your scene

在预先设置的层上,EasyTouch自动检测所有gameobjects的碰撞体。很容易处理组成你的场景的各种元素。

EasyTouch is written in C# , it notifies you of an action on the touch screen or with mouse by firing events. The events are sent by delegate system for C #, or you can use EasyTouchTrigger component is you are not familiar with events.

EasyTouch是用c#编写的,它通知你在触摸屏或鼠标的行为是通过触发事件。发送事件可以通过C#的委托,也可以通过EasyTouchTrigger组件中所不熟悉的事件。

Each event passes a parameter class, with all the informations about the current action (position, angle, picked object …)

每个事件传递一个参数类,包含当前行为的所有信息。

Quick start

· Import EasyTouch package

· Right click on hierarchy view => EasyTouch => Add EasyTouch

· Create a new C# script MyFirstTouch

· Add these methods

// Subscribe to events

void OnEnable(){

EasyTouch.On_TouchStart += On_TouchStart;

}

// Unsubscribe

void OnDisable(){

EasyTouch.On_TouchStart -= On_TouchStart;

}

// Unsubscribe

void OnDestroy(){

EasyTouch.On_TouchStart -= On_TouchStart;

}

// Touch start event

public void On_TouchStart(Gesture gesture){

Debug.Log( "Touch in " + gesture.position);

}

· Create an empty gameObject, and name it Receiver.

· Add MyFirstTouch script to the gameObject Receiver.

· Run it in editor, and click on the screen

Quick start with auto-selection

· Import EasyTouch package

· Right click on hierarchy view => EasyTouch => Add EasyTouch

· Create a new C# script

· Add these methods

// Subscribe to events

void OnEnable(){

EasyTouch.On_TouchStart += On_TouchStart;

}

// Unsubscribe

void OnDisable(){

EasyTouch.On_TouchStart -= On_TouchStart;

}

// Unsubscribe

void OnDestroy(){

EasyTouch.On_TouchStart -= On_TouchStart;

}

// At the touch beginning

public void On_TouchStart(Gesture gesture){

// chack that we have touched the sphere

if (gesture.pickedObject == gameObject)

gameObject.renderer.material.color = new Color( Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f));

}

· Create a sphere and assign it a simple diffuse material

· Add script on the sphere

· Run it in editor, and click on the screen

EasyTouchTrigger

EasyTouchTrigger is a new component that allow you to easily & quickly use EasyTouch.It can be used instead or in addition to the conventional method by C# event.

This component allows you to call functions on GameObjects according EasyTouch events without writing a line of code.

How does it work?

ETT allows you to define the object which will receive a gesture and the object on which you want to execute a function. You still have to specify the function name, and if necessary the parameter to send.

How to use ETT (Look at video on Youtube)

· Select the gameobject to interact with the touch screen, or one that will serve as a scheduler. You can add as many as you like EasyTouchTrigger.

选择gameobject与触摸屏交互,或者将作为调度器。您可以添加多个你喜欢的EasyTouchTrigger。

· Add ETT component with Add Component button => Event => EasyTouch Trigger

 

· The component is now active on your gameobject

· You can now add EasyTouch event by clicking on Add new event. A context menu will display all available events

EasyTouchTrigger Inspector

Enable + T rigger Name

Enables or disable this trigger

启用或禁用 触发器名称

Restricted to gameobject

对象限制

Enable The beginning of the gesture must be on the current gameobject to trigger the action.

启用:必须在当前对象上开始触发动作。

Disable

GameObject

Sets the selectable gameobject which will receive the start of the gesture to trigger the action.

选择一个开始触发动作的对象

Null The action will be triggered in all cases

NULL:在所有情况下都将触发的动作

Other receiver

Disable

The message will be sent to the gameobject current.

禁用:消息将发送给当前对象

Enable

Sets the gameobject which will receive the message

启用:设置可以接收消息的对象

Method name

The public function to call

调用方法的名称

Parameter to send

The property of the gesture class to send

以参数形式发送的手势的属性

EasyTouch Inspector

Enable EasyTouch

Enables or disables EasyTouch. No events will be fired if EasyTouch is disabled

启用或禁用EasyTouch。禁用时,所有事件不被触发。

Enable Unity Remote

Enabled this option if you want to test multi-finger on Unity Remote. (Don’t forget to remove this flag before your final build)

在Unity Remote上测试多个手指

GUI Compatibility

Allow you to setup the behaviour of EasyTouch with NGUI & Unity UI

Automatic selection

Allow you ti setup the auto-seleciton.

General gesture properties

Allow you to setup simple gesture

Two fingers gesture properties

Allow you to setup two finger gesture

Second finger simulation

Allow you to setup the second finger simulation

GUI Compatibility

Enable Uniyt UI detection

Enables or disables detection of selectable UI Element

启用或禁用可选择的UI元素的检测情况

Unity UI compatibility

UGUI兼容性

Enable EasyTouch doesn’t fire gesture events if touch is over a UIElement.

启用:如果触摸UIElement,EasyTouch不触发手势事件。

Disable EasyTouch fires gesture events, and set isOverUIElement to true for gesture class

禁用:触发手势事件,会设置gesture类中的isOverUIElement属性值为true。

Auto update picked Unity UI

Enable EasyTouch update UI data at each frame

启用EasyTouch每一帧更新UI数据

Enable NGUI Compatibility

Enable detection of NGUI object relative to NGUILAyers & Camera. EasyTouch doesn’t fire gesture event if touch is over NGUI Object.

触摸NGUI不触发任何事件

NGUI Layers

Layers mask for NGui object

所在层

Camera

All cameras for NGui detection

所用摄像机

Automatic selection

Enable auto-select

enables 3D object detection under the touch relative to the setting.

启用3D对象检测

pickable layers 3D

Layer mask for selectable objects.

检测3D对象的层

Auto update picked gameobject

EasyTouch update picked object at each frame

每一帧更新选择的对象

Enable 2D collider

Enable 2Dcollider detection

启用2D碰撞器检测

pickable 2D layers

Layer mask for selectable 2D objects.

检测2D对象的层

General gesture properties

Priority to

You can choose between giving priority to tap gesture or slips gesture.

优先级设置

Tap Stationary tolerance takes into account to detect a move from the current touch.

点击:Stationary tolerance设置的值为察觉屏幕上移动的值(小于这个值视为点击)

Slips Stationary tolerance doesn’t take into account to detect move. The motion is detect by Unity API (more reactive)

滑动:Stationary tolerance设置的值为不考虑移动的值(大于这个值视为移动)

Stationary tolerance

It’s a diameter in pixel in which the key is considered stationary for Tap priority

固定公差:像素直径内是点击

Long tap time

The time required to detect a long tap

长按时间设置

Double tap time

The maximum time to detect a double tap

双击最大时间

Swipe tolerance

The detection threshold between different build in swipe direction

在不同构建之间的滑动方向的阀值

Two fingers gesture properties

2 Fingers gesture

Enables 2 fingers gesture

启用双手指模式

Pick method

Can choose between 2 methods for auto-selection

Finger the fingers must be over the object. 手指必须在对象。

Average It takes into account the average position to detect object它考虑了平均位置检测对象

Enable swipe & drag

Enable swipe or drag gesture

启用滑动和拖拽的手势

Enable Pinch

Enable pinch gesture

启用捏的手势

Min pinch length

The minimum threshold distance in pixel for detecting a pinch

最小捏的距离

Enable twist

Enable twist gesture

启用扭曲的手势

Min twist angle

The minimum threshold angle for detecting a twist

最小扭曲角度

Second finger simulation

Enable simulation

Enables second finger simulation

启用第二手指模拟

T exture

The picture to display

图片

T wist & pinch key / Swipe key

Key to activate the simulation

按键配置

Welcome to the EasyTouch Scripting Reference!

This section of the documentation contains details of the scripting API that EasyTouch provides. To use this information, you should be familiar with the basic theory and practice of scripting in Unity.

EasyTouch

Enumerations 枚举

GesturePriority

Gesture priority Tap, Slips

手势优先级

 

SwipeDirection

Build in swipe direction None, Left, Right, Up, Down, UpLeft, UpRight, DownLeft, DownRight, Other

滑动方向

 

TwoFingerPickMethod

2 fingers pick method Finger, Average

选择方式

 

Static functions

SetEnabled

Enables or disables EasyTouch.

GetEnabled

Return true is EasyTouch is enabled.

SetUICompatibily

Enables or disables Unity UI compatibility.

GetUIComptability

Return true is Unity UI compatibility is enabled.

SetAutoUpdateUI

Enables or disables auto-update picked UI element.

GetAutoUpdateUI

Return true if auto-update UI element is enabled.

SetEnableAutoSelect

Enables or disables auto selection.

GetEnableAutoSelect

Return true if auto-selection is enabled

SetAutoUpdatePickedObject

Enables or disable auto-update picked object.

GetAutoUpdatePickedObject

Return true if auto-update picked object is enabled.

Set3DPickableLayer

Set layer mask for selectable object.

Get3DPickableLayer

Return the layer mask for selectable object.

AddCamera

Add a camera for selectable object.

RemoveCamera

Remove a camera.

GetCamera

Return a camera.

SetEnable2DCollider

Enables or disables 2D collider detection.

GetEnable2DCollider

Return true if 2D collider detection is enabled.

Set2DPickableLayer

Set layer mask for 2d selectable object.

Get2DPickableLayer

Get layer mask for 2D selectable object.

SetGesturePriority

Set the gesture priority.

GetGesturePriority

Return the gesture priority.

SetStationaryTolerance

Set the stationary tolerance.

GetStationaryTolerance

Get the stationary tolerance

SetLongTapTime

Set the long tap time.

GetlongTapTime

Get the long tap time.

SetDoubleTapTime

Set the double tap time.

GetDoubleTapTime

Get the double tap time.

SetSwipeTolerance

Set the swipe tolerance

GetSwipeTolerance

Get the swipe tolerance

SetEnable2FingersGesture

Enables or disables 2 fingers gestures.

GetEnable2FingersGesture

Return true if 2 fingers gesture is enabled.

SetTwoFingerPickMethod

Set the 2 fingers selectable method.

GetTwoFingerPickMethod

Return the 2 fingers selectable method.

SetEnablePinch

Enables or disables pinch gesture.

GetEnablePinch

Return true if pinch gesture is enabled.

SetMinPinchLength

Set the min pinch detection length.

GetMinPinchLength

Return the min pinch detection lenght.

SetEnableTwist

Enables or disables twist gesture.

GetEnableTwist

Return true if twist gesture is enabled

SetMinTwistAngle

Set the min twist angle detection

GetMinTwistAngle

Get the min twist angle

GetSecondeFingerSimulation

Enables or disables second finger simulation.

SetSecondFingerSimulation

Return true if second finger simulation is enabled.

Events

Each event is firing with a parameter of type Gesture.

Single finger events

On_Cancel

Occurs when The system cancelled tracking for the touch.

取消

On_TouchStart

Occurs when a finger touched the screen.

开始触摸

On_TouchDown

Occurs while as the touch is active.

按下

On_TouchUp

Occurs when a finger was lifted from the screen.

抬起

On_SimpleTap

Occurs when a finger was lifted from the screen

单击

On_DoubleTap

Occurs when the number of taps is equal to 2 in giving time.

双击

On_LongTapStart

Occurs when a finger is touching the screen, but hasn’t moved since the time required for the detection of a long tap.

长按开始

On_LongTap

Occurs while as the touch is active after a LongTapStart.

长按

On_LongTapEnd

Occurs when a finger was lifted from the screen after a long tap.

长按结束

On_DragStart

Occurs when a drag start. A drag is a swipe on a selectable object

拖拽开始

On_Drag

Occurs while as the drag is active.

拖拽

On_DragEnd

Occurs when a finger that raise the drag event , is lifted from the screen.

拖拽结束

On_SwipeStart

Occurs when swipe start.

滑动开始

On_Swipe

Occurs while as the swipe is active.

滑动

On_SwipeEnd

Occurs when a finger that raise the swipe event , is lifted from the screen.

滑动结束

Two finger events

On_TouchStart2Fingers

Like On_TouchStart but for a 2 fingers gesture.

On_TouchDown2Fingers

Like On_TouchDown but for a 2 fingers gesture.

On_TouchUp2Fingers

Like On_TouchUp but for a 2 fingers gesture.

On_SimpleTap2Fingers

Like On_SimpleTap but for a 2 fingers gesture.

On_DoubleTap2Fingers

Like On_DoubleTap but for a 2 fingers gesture.

On_LongTapStart2Fingers

Like On_LongTapStart but for a 2 fingers gesture

On_LongTap2Fingers

Like On_LongTap but for a 2 fingers gesture.

On_LongTapEnd2Fingers

Like On_LongTapEnd but for a 2 fingers gesture.

On_Twist

Occurs while a twist gesture.

On_TwistEnd

Occurs at twist gesture end.

On_Pinch

Occurs while as the pinch gesture is active.

On_PinchIn

Occurs while as the pinch in gesture is active.

On_PinchOut

Occurs while as the pinch out gesture is active.

On_PinchEnd

Occurs when the 2 fingers that raise the pinch event , are lifted from the screen.

On_DragStart2Fingers

Like On_DragStart but for a 2 fingers gesture.

On_Drag2Fingers

Like On_Drag but for a 2 fingers gesture.

On_DragEnd2Fingers

Like On_DragEnd but for a 2 fingers gesture.

On_SwipeStart2Fingers

Like On_SwipeStart but for a 2 fingers gesture.

On_Swipe2Fingers

Like On_Swipe but for a 2 fingers gesture.

On_SwipeEnd2Fingers

Like On_SwipeEnd but for a 2 fingers gesture.

Unity UI

On_OverUIElement

Occurs when the touch is over a UI element when Unity Ui compatibility is On

On_UIElementUp

Occurs when the touch is lifted from UI element when Unity Ui compatibility is On

Gesture

Each event is firing with a parameter of type Gesture. It contains all information about the current gesture.

Variables

fingerIndex

The index of the finger that fired the event, or -1 for a two fingers gesture

手指索引

touchCount

The number of active touches.

触摸个数

startPosition

The start position of the current gesture that fired the event.

起始位置

position

The current position of the current gesture that fired the event.

当前位置

deltaPosition

The delta position since last call.

流逝的位置增量

actionTime

The elapsed time in second since the begin of gesture.

自开始手势以来的运行时间(秒)

deltaTime

The delta time since last call.

流逝的时间

swipe

The swipe or drag direction.

滑动或者拖拽的方向

swipeLength

The swipe length in pixel.

滑动的像素距离

swipeVector

The swipe vector direction.

滑动的方向

deltaPinch

The delta pinch length in pixel since last call.

自上一次调用捏的长度增量

twistAngle

The delta angle of the twist since the last call.

扭曲的角度

twoFingerDistance

The distance in pixel between two finger for a two finger gesture.

连个手指之间的距离(像素)

pickedObject

The current picked gameObject.

选择的对象

pickedCamera

The picked camera.

选择的摄像机

isGuiCamera

Is the picked camera is flag as GUI

是否是GUI摄像机

isOverGui

Is the current touch is over an Unity UI.

是否在UGUI上

pickedUIElement

The current picked Unity UI.

选择的UGUI

Functions

GetTouchToWordlPoint

Transforms touch position from screen space into world space.

获取触摸点的世界坐标

GetSwipeOrDragAngle

Gets the swipe or drag angle.

获取滑动或拖拽的角度

NormalizedPosition

Gets the normalized position.

获取位置的标准化

GetCurrentPickedObject

Gets the real picked object under the touch

获取当前选择的对象

IsOverUIElement

Is the current touch is over an Unity UI.

当前触摸是否在UI上

IsOverRectTransform

Is the current touch is over a specific RectTransform. GetCurrentFirstPickedUIElement Gets the real picked Unity UI under the touch.

当前的触摸是否在RectTransform上

Gesture.fingerIndex

public int fingerIndex

Description

The index of the finger that fired the event, or -1 for a two fingers gesture. Useful for managing the multi- touches.

Gesture.touchCount

public int touchCount

Description

The number of active touches. Useful for managing the multi-touches.

Gesture.startPosition

public Vector2 startPosition

Description

The start position of the current gesture that fired the event, or the average position between the 2 touches for a two fingers gesture.

Gesture.position

public Vector2 position

Description

The current position of the current gesture that fired the event, or the average position between the 2 touches for a two fingers gesture.

Gesture.deltaPosition

public Vector2 deltaPosition

Description

The delta position since last call. EasyTouch computes is own delta to prevent difference between all mobile platform.

Gesture.actionTime

public float actionTime

Description

The elapsed time in second since the begin of gesture.

Gesture.deltaTime

public float deltaTime

Description

The delta time since last call.

Gesture.swipe

public EasyTouch.SwipeDirection swipe

Description

The swipe or drag direction. This value is calculated with the deltaPositon for current gesture, and between startPosition and current position for gesture end.

Gesture.swipeLength

public float swipeLength

Description

The swipe length in pixel. This value is computed for end gesture between startPosition and position.

Gesture.swipeVector

public Vector2 swipeVector

Description

The swipe vector direction.

Gesture.deltaPinch

public float deltaPinch

Description

The delta pinch length in pixel since last call.

This value is positive for On_PinchIn & On_PinchOut events

This value is positive for pinch out gesture, and negative for pinch in gesture for On_Pinch event.

Gesture.twistAngle

public float twistAngle

Description

The delta angle of the twist since the last call.

Negative value for clockwise. Positive value for anit-clockwise.

Gesture.twoFingerDistance

public float twoFingerDistance

Description

The distance in pixel between two finger for a two finger gesture.

Gesture.pickedObject

public GameObject pickedObject

Description

The current picked gameObject detected at the touch start, or the real object under the touch position if auto update is enabled.

Gesture.pickedCamera

public Camera pickedCamera

Description

The picked camera for find the picked object.

Gesture.isGuiCamera

public bool isGuiCamera

Description

Is the picked camera is flag as GUI

Gesture.isOverGUI

public bool isOverGui

Description

The current touch is over an Unity UI element detected at the touch start, or update in real time is auto- update is enabled.

This value is correct only when the Ui Compatibility Mode is disabled, otherwise it will always be equal to false.

Gesture.pickedUIElement

public GameObject pickedUIElement

Description

The current picked Unity UI element detected at the touch start, or update in real time is auto-update is enabled.

This value is correct only when the Ui Compatibility Mode is disabled, otherwise it will always be equal to Null.

Gesture.GetTouchToWorldPoint

public Vector3 GetTouchToWorldPoint(float z)

Description

Transforms the current touch position from screen space into world space. The z position is in world units from the camera.

public Vector3 GetTouchToWorldPoint(Vector3 position3D)

Description

Transforms the current touch position from screen space into world space.

position3D is a the destination world position, from that will be computed the length from the camera.

Gesture.GetSwipeOrDragAngle

public float GetSwipeOrDragAngle()

Description

Return the swipe or drag angle.

Gesture.NormalizedPosition

public Vector2 NormalizedPosition()

Description

Return the normalized position relative to screen.

Gesture.GetCurrentPickedObject

public GameObject GetCurrentPickedObject()

Description

Gets the real picked object. You don’t need to use the functions, if auto-update is enabled.

Gesture.IsOverUIElement

public bool IsOverUIElement()

Description

Return true if current touch is over an Unity UI element

Gesture.IsOverRectTransform

public bool IsOverRectTransform(RectTransform tr, Camera camera=null)

Description

Return true if current touch is a recttransform.

Gesture.GetCurrentFirstPickedUIElement

public GameObject GetCurrentFirstPickedUIElement()

Description

Gets the real picked Unity UI Element. You don’t need to use the functions, if auto-update is enabled.

C#程序员整理的Unity 3D笔记(十一):unity3d中脚本生命周期(MonoBehaviour lifecycle)

脚本自带函数执行顺序,看看下图即可明白。唯一需要注意的是,要注意函数字符的大小写—这个是C#程序员容易被坑的地方之一。

 

clip_image002  C#程序员整理的Unity 3D笔记(十一):unity3d中脚本生命周期(MonoBehaviour lifecycle) clip image002 thumb

最先执行的方法是Awake,这是生命周期的开始,用于进行激活时的初始化代码,一般可以在这个地方将当前脚本禁用:this.enable=false,如果这样做了,则会直接跳转到OnDisable方法执行一次,然后其它的任何方法,都将不再被执行。

如果当前脚本处于可用状态,则正常的执行顺序是继续向下执行OnEnable,当然我们可以在另外一个脚本中实现这个脚本组件的启动:this.enable =true;

再向下执行,会进行一个判断,如果Start方法还没有被执行,则会被执行一次,如果已经被执行了,则不会再被执行。这是个什么意思呢?我们可以在某个脚本中将组件禁用this.enable=false,再启用时会转到OnEnable处执行,这时继续向下走,发现Start执行过了,将不再被执行。比如说:第一次启用时,将怪物的初始位置定在了(0,0,0)点,然后怪物可能会发生了位置的变换,后来被禁用了,再次启用时,不会让怪物又回到初始的(0,0,0)位置。

继续向后执行,就是FixedUpdate了,然后是Update,再然后是LateUpdate,如果后面写了Reset,则会又回到Update,在这4个事件间可以进行循环流动。

再向后执行,就进入了渲染模块(Rendering),非常重要的一个方法就是OnGUI,用于绘制图形界面。当然,如果你使用了NGUI,这个生命周期的事情你就不用考虑了。

再向后,就是卸载模块(TearDown),这里主要有两个方法OnDisableOnDestroy。当被禁用(enable=false)时,会执行OnDisable方法,但是这个时候,脚本并不会被销毁,在这个状态下,可以重新回到OnEnable状态(enable=true)。当手动销毁或附属的游戏对象被销毁时,OnDestroy才会被执行,当前脚本的生命周期结束。

脚本自带函数执行顺序如下:将下面脚本挂在任意物体运行即可得到

Awake ->OnEable-> Start -> -> FixedUpdate-> Update  -> LateUpdate ->OnGUI ->Reset -> OnDisable ->OnDestroy

  • 1.Awake:用于在游戏开始之前初始化变量或游戏状态。在脚本整个生命周期内它仅被调用一次.Awake在所有对象被初始化之后调用,所以你可以安全的与其他对象对话或用诸如GameObject.FindWithTag()这样的函数搜索它们。每个游戏物体上的Awake以随机的顺序被调用。因此,你应该用Awake来设置脚本间的引用,并用Start来传递信息Awake总是在Start之前被调用。它不能用来执行协同程序。
  • 2.Start:仅在Update函数第一次被调用前调用。Start在behaviour的生命周期中只被调用一次。它和Awake的不同是Start只在脚本实例被启用时调用。你可以按需调整延迟初始化代码。Awake总是在Start之前执行。这允许你协调初始化顺序。在所有脚本实例中,Start函数总是在Awake函数之后调用。
  • 3.FixedUpdate:固定帧更新,在Unity导航菜单栏中,点击“Edit”–>“Project Setting”–>“Time”菜单项后,右侧的Inspector视图将弹出时间管理器,其中“Fixed Timestep”选项用于设置FixedUpdate()的更新频率,更新频率默认为0.02s。
  • 4.Update:正常帧更新,用于更新逻辑。每一帧都执行,处理Rigidbody时,需要用FixedUpdate代替Update。例如:给刚体加一个作用力时,你必须应用作用力在FixedUpdate里的固定帧,而不是Update中的帧。(两者帧长不同)FixedUpdate,每固定帧绘制时执行一次,和update不同的是FixedUpdate是渲染帧执行,如果你的渲染效率低下的时候FixedUpdate调用次数就会跟着下降。FixedUpdate比较适用于物理引擎的计算,因为是跟每帧渲染有关。Update就比较适合做控制。
  • 5.LateUpdate:在所有Update函数调用后被调用,和fixedupdate一样都是每一帧都被调用执行,这可用于调整脚本执行顺序。例如:当物体在Update里移动时,跟随物体的相机可以在LateUpdate里实现。LateUpdate,在每帧Update执行完毕调用,他是在所有update结束后才调用,比较适合用于命令脚本的执行。官网上例子是摄像机的跟随,都是在所有update操作完才跟进摄像机,不然就有可能出现摄像机已经推进了,但是视角里还未有角色的空帧出现。
  • 6.OnGUI:在渲染和处理GUI事件时调用。比如:你画一个button或label时常常用到它。这意味着OnGUI也是每帧执行一次。
  • 7.Reset:在用户点击检视面板的Reset按钮或者首次添加该组件时被调用。此函数只在编辑模式下被调用。Reset最常用于在检视面板中给定一个默认值。
  • 8.OnDisable:当物体被销毁时 OnDisable将被调用,并且可用于任意清理代码。脚本被卸载时,OnDisable将被调用,OnEnable在脚本被载入后调用。注意: OnDisable不能用于协同程序。
  • 9.OnDestroy:当MonoBehaviour将被销毁时,这个函数被调用。OnDestroy只会在预先已经被激活的游戏物体上被调用。注意:OnDestroy也不能用于协同程序。

C#程序员整理的Unity 3D笔记(八):Unity 3D坐标系介绍

1World Space(世界坐标):
我们在场景中添加物体(如:Cube),他们都是以世界坐标显示在场景中的。
transform.position可以获得该位置坐标。
2Screen Space(屏幕坐标):
以像素来定义的,以屏幕的左下角为(0,0)点,右上角为(Screen.width,Screen.height),Z的位置是以相机的世界单位来衡量的。
Screen.width = Camera.pixelWidth
Screen.height = Camera.pixelHeigth
鼠标位置坐标属于屏幕坐标,Input.mousePosition可以获得该位置坐标,
手指触摸屏幕也为屏幕坐标,Input.GetTouch(0).position可以获得单个手指触摸屏幕坐标。
clip_image001  C#程序员整理的Unity 3D笔记(八):Unity 3D坐标系介绍 clip image001 thumb

3ViewPort Space(视口坐标):
视口坐标是标准的和相对于相机的。相机的左下角为(0,0)点,右上角为(1,1)点,Z的位置是以相机的世界单位来衡量的。
clip_image002  C#程序员整理的Unity 3D笔记(八):Unity 3D坐标系介绍 clip image002 thumb
4、绘制GUI界面的坐标系:
这个坐标系与屏幕坐标系相似,不同的是该坐标系以屏幕的左上角为(0,0)点,右下角为(Screen.width,Screen.height)。
clip_image003  C#程序员整理的Unity 3D笔记(八):Unity 3D坐标系介绍 clip image003 thumb

【四种坐标系的转换】
1
、世界坐标屏幕坐标:
camera.WorldToScreenPoint(transform.position);
这样可以将世界坐标转换为屏幕坐标。其中camera为场景中的camera对象。
2、屏幕坐标视口坐标:
camera.ScreenToViewportPoint(Input.GetTouch(0).position);
这样可以将屏幕坐标转换为视口坐标。其中camera为场景中的camera对象。
3、视口坐标屏幕坐标:
camera.ViewportToScreenPoint();
4、视口坐标世界坐标:
camera.ViewportToWorldPoint();

C#程序员整理的Unity 3D笔记(四):脚本优化

Unity3D代码开发需要注意的地方

1. 尽量避免每帧处理

比如:

function Update() { DoSomeThing(); }

可改为每5帧处理一次:

function Update() { if(Time.frameCount % 5 == 0) { DoSomeThing(); } }

2. 定时重复处理用 InvokeRepeating 函数实现

比如,启动0.5秒后每隔1秒执行一次 DoSomeThing 函数:

function Start() { InvokeRepeating("DoSomeThing", 0.5, 1.0); }

3. 优化 Update, FixedUpdate, LateUpdate 等每帧处理的函数

Update() 和 FixedUpdate()在游戏中都会在更新的时候自动循环调用。

但是Update是在每次渲染新的一帧的时候才会调用,也就是说,这个函数的更新频率和设备的性能有关以及被渲染的物体(可以认为是三角形的数量)。在性能好的机器上可能fps 30,差的可能小些。这会导致同一个游戏在不同的机器上效果不一致,有的快有的慢。因为Update的执行间隔不一样了。

而FixedUpdate,是在固定的时间间隔执行,不受游戏帧率的影响。有点想Tick。所以处理Rigidbody的时候最好用FixedUpdate。

Unity中Update和Lateupdate的区别。Lateupdate和Update每一祯都被执行,但是执行顺序不一样,先执行Updatee然后执行lateUpdate。

如果你有两个脚本JS1、JS2,两个脚本中都有Update()函数, 在JS1中有 lateUpdate ,JS2中没有。那么 lateUpdate 函数会等待JS1、JS2两个脚本的Update()函数 都执行完后才执行。也就是说, 如果现在有100个脚本,分别有100个 Update()函数,其中只有一个LateUpdate,那么在同一祯中,等待100个Update()执行完后,才执行这一个lateUpdate()。

函数里面的变量尽量在头部声明。

比如:

function Update() { var pos: Vector3 = transform.position; }

可改为

private var pos: Vector3; function Update(){ pos = transform.position; }

4. 主动回收垃圾

给某个 GameObject 绑上以下的代码:

function Update() { if(Time.frameCount % 50 == 0) { System.GC.Collect(); } }

5. 运行时尽量减少 Tris Draw Calls

预览的时候,可点开 Stats,查看图形渲染的开销情况。特别注意 Tris 和 Draw Calls 这两个参数。

一般来说,要做到:

Tris 保持在 7.5k 以下

Draw Calls 保持在 20 以下

Tris:Game 视窗右上角 Stat 里面的Tris 记录场景内的所有三角面数

Draw Calls:

一个简单的openGL的绘图次序是:设置颜色→绘图方式→顶点座标→绘制→结束。

每帧都会重复以上的步骤。这就是一次draw call

如果有两个model,那么需要

设置颜色→绘图方式→顶点座标A→绘制→结束。

设置颜色→绘图方式→顶点座标B→绘制→结束。

两次draw calls;

也就是说在openGl绘制前,如果色彩通道(color filter),绘图方式(shader),顶点座标(model)不同的情况下draw calls就会增加。

对openGl来说绘制参数(状态值)的变更要比绘制大量的顶点更耗费cpu。

所谓高速绘图就是,在尽量不改变openGl状态值的情况下,用一次draw call完成所有绘制。

比如上面的例子:

设置颜色→绘图方式→顶点座标A+顶点座标B→绘制→结束。

就要更加有效率。

6. 压缩 Mesh

导入 3D 模型之后,在不影响显示效果的前提下,最好打开 Mesh Compression。

Off, Low, Medium, High 这几个选项,可酌情选取。

7. 避免大量使用 Unity 自带的 Sphere 等内建 Mesh

Unity 内建的 Mesh,多边形的数量比较大,如果物体不要求特别圆滑,可导入其他的简单3D模型代替。

8. 优化数学计算

比如,如果可以避免使用浮点型(float),尽量使用整形(int),尽量少用复杂的数学函数比如 Sin 和 Cos 等等

9. 减少固定增量时间

将固定增量时间值设定在0.04-0.067区间(即,每秒15-25帧)。您可以通过Edit->Project Settings->Time来改变这个值。这样做降低了FixedUpdate函数被调用的频率以及物理引擎执行碰撞检测与刚体更新的频率。如果您使用了较低的固定增量时间,并且在主角身上使用了刚体部件,那么您可以启用插值办法来平滑刚体组件。

10. 减少GetComponent的调用

使用 GetComponent或内置组件访问器会产生明显的开销。您可以通过一次获取组件的引用来避免开销,并将该引用分配给一个变量(有时称为"缓存"的引用)。例如,如果您使用如下的代码:

function Update () {

transform.Translate(0, 1, 0);

}

通过下面的更改您将获得更好的性能:

var myTransform : Transform;

function Awake () {

myTransform = transform;

}

function Update () {

myTransform.Translate(0, 1, 0);

}

11. 避免分配内存

您应该避免分配新对象,除非你真的需要,因为他们不再在使用时,会增加垃圾回收系统的开销。您可以经常重复使用数组和其他对象,而不是分配新的数组或对象。这样做好处则是尽量减少垃圾的回收工作。同时,在某些可能的情况下,您也可以使用结构(struct)来代替类(class)。这是因为,结构变量主要存放在栈区而非堆区。因为栈的分配较快,并且不调用垃圾回收操作,所以当结构变量比较小时可以提升程序的运行性能。但是当结构体较大时,虽然它仍可避免分配/回收的开销,而它由于"传值"操作也会导致单独的开销,实际上它可能比等效对象类的效率还要低。

12. 使用iOS脚本调用优化功能

UnityEngine 命名空间中的函数的大多数是在 C/c + +中实现的。从Mono的脚本调用 C/C++函数也存在着一定的性能开销。您可以使用iOS脚本调用优化功能(菜单:Edit->Project Settings->Player)让每帧节省1-4毫秒。此设置的选项有:

Slow and Safe – Mono内部默认的处理异常的调用

Fast and Exceptions Unsupported –一个快速执行的Mono内部调用。不过,它并不支持异常,因此应谨慎使用。它对于不需要显式地处理异常(也不需要对异常进行处理)的应用程序来说,是一个理想的候选项。

13. 优化垃圾回收

如上文所述,您应该尽量避免分配操作。但是,考虑到它们是不能完全杜绝的,所以我们提供两种方法来让您尽量减少它们在游戏运行时的使用:

如果堆比较小,则进行快速而频繁的垃圾回收

这一策略比较适合运行时间较长的游戏,其中帧率是否平滑过渡是主要的考虑因素。像这样的游戏通常会频繁地分配小块内存,但这些小块内存只是暂时地被使用。如果在iOS系统上使用该策略,那么一个典型的堆大小是大约 200 KB,这样在iPhone 3G设备上,垃圾回收操作将耗时大约 5毫秒。如果堆大小增加到1 MB时,该回收操作将耗时大约 7ms。因此,在普通帧的间隔期进行垃圾回收有时候是一个不错的选择。通常,这种做法会让回收操作执行的更加频繁(有些回收操作并不是严格必须进行的),但它们可以快速处理并且对游戏的影响很小:

if (Time.frameCount % 30 == 0)

{

System.GC.Collect();

}

但是,您应该小心地使用这种技术,并且通过检查Profiler来确保这种操作确实可以降低您游戏的垃圾回收时间

如果堆比较大,则进行缓慢且不频繁的垃圾回收

这一策略适合于那些内存分配 (和回收)相对不频繁,并且可以在游戏停顿期间进行处理的游戏。如果堆足够大,但还没有大到被系统关掉的话,这种方法是比较适用的。但是,Mono运行时会尽可能地避免堆的自动扩大。因此,您需要通过在启动过程中预分配一些空间来手动扩展堆(ie,你实例化一个纯粹影响内存管理器分配的"无用"对象):

function Start() {

var tmp = new System.Object[1024];

// make allocations in smaller blocks to avoid them to be treated in a special way, which is designed for large blocks

for (var i : int = 0; i < 1024; i++)

tmp[i] = new byte[1024];

// release reference

tmp = null;

}

游戏中的暂停是用来对堆内存进行回收,而一个足够大的堆应该不会在游戏的暂停与暂停之间被完全占满。所以,当这种游戏暂停发生时,您可以显式请求一次垃圾回收:

System.GC.Collect();

另外,您应该谨慎地使用这一策略并时刻关注Profiler的统计结果,而不是假定它已经达到了您想要的效果。

unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010

本文以Unity 3D 4.5.5 和Visual Studio 2010为例,简介一下搭建开发环境(含破解),并配置超级无敌的VS 2010 进行C#代码调试.

1. UnitySetup-4.5.5.exe

官网下载最新版本4.X

安装exe文件

clip_image001  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image001 thumb

2. Unity 4.x Pro Patch.exe

复制exe到安装目录下

C:Program Files (x86)UnityEditor

运行exe

clip_image002  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image002 thumb

点击Browse,选择文件夹C:Program Files (x86)UnityEditor

点击path

点击Rand

点击Cre Lic

破解完成

3. Visual Studio 2010 Tools for Unity.msi

安装2010插件包(其他版本例如2012,2013插件包请在网上下载)

打开unity软件

对新建的项目导入vs2010插件

clip_image004  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image004 thumb

打开软件的配置界面

clip_image006  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image006 thumb

在弹出窗口中选择vs2010工具来编辑脚本

clip_image007  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image007 thumb

双击C#脚本,打开vs2010,点击调试菜单

clip_image009  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image009 thumb

在弹出窗口中,选择需要调试的项目,点击OK。这样就可以用vs2010代替自带的脚本编辑器来编写代码和调试程序。

clip_image010  unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010 clip image010 thumb