Unity 技巧集合

(来自:http://unity3d.9tech.cn/news/2014/0109/39576.html)


这篇文章将收集unity的相关技巧,会不断地更新内容。

1)保存运行中的状态

unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在 “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。

2)Layer的用法

LayerMask.NameToLayer("Ground");  // 通过名字获取layer

3D Raycast

1
2
3
4
RaycastHit hit;
if (Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, (1<<LayerMask.NameToLayer( "Ground" )))) {
...
}
2D Raycast
1
2
3
4
Collider2D h = Physics2D.OverlapPoint(cam2d.ScreenToWorldPoint(Input.mousePosition), (1<<LayerMask.NameToLayer( "xxx" ))); 
if (h) { 
... 
}
3)物理摄像头取色( WebCamTexture)
1
2
3
4
5
6
7
Texture2D exactCamData() {
     // get the sample pixels
     Texture2D snap = new Texture2D((int)detectSize.x, (int)detectSize.y);
     snap.SetPixels(webcamTexture.GetPixels((int)detectStart.x, (int)detectStart.y, (int)detectSize.x, (int)detectSize.y));
     snap.Apply();
     return snap;
}
保存截图:
1
System.IO.File.WriteAllBytes(Application.dataPath + "/test.png" , exactCamData().EncodeToPNG());

4) 操作componenent

添加:

1
2
CircleCollider2D cld = (CircleCollider2D)colorYuan[i].AddComponent( typeof (CircleCollider2D));
cld.radius = 1;
删除:
1
Destroy(transform.gameObject.GetComponent<SpriteRenderer>());

5)动画相关

Unity 技巧集合_第1张图片

状态Init到状态fsShake的的条件为:参数shake==true;代码中的写法:

触发fsShake:

1
2
3
4
5
6
7
void Awake() {
     anims = new Animator[(int)FColorType.ColorNum];
}
....
if (needShake) {
     curAnim.SetTrigger( "shake" );
}
关闭fsShake
1
2
3
4
5
6
7
8
9
10
11
12
void Update() {
....
if (curAnim) {
     AnimatorStateInfo stateInfo = curAnim.GetCurrentAnimatorStateInfo(0);
     if (stateInfo.nameHash == Animator.StringToHash( "Base Layer.fsShake" )) {
         curAnim.SetBool( "shake" , false );
         curAnim = null ;
         print ( "======>>>>> stop shake!!!!" );
     }
}
....
}

6)scene的切换

同步方式:

1
Application.LoadLevel(currentName);
异步方式:
1
Application.LoadLevelAsync( "ARScene" );
7)加载资源
1
Resources.Load<Texture>(string.Format( "{0}{1:D2}" , mPrefix, 5));

8)Tag VS. Layer

     -> Tag用来查询对象

     -> Layer用来确定哪些物体可以被raycast,还有用在camera render中

9)旋转

transform.eulerAngles 可以访问 rotate的 xyz 
1
transform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);
10)保存数据
1
PlayerPrefs.SetInt( "isInit_" + Application.loadedLevelName, 1);

11)动画编码

http://www.cnblogs.com/lopezycj/archive/2012/05/18/Unity3d_AnimationEvent.html

http://game.ceeger.com/Components/animeditor-AnimationEvents.html

http://answers.unity3d.com/questions/8172/how-to-add-new-curves-or-animation-events-to-an-im.html

12) 遍历子对象

1
2
3
4
5
Transform[] transforms = target.GetComponentsInChildren<Transform>(); 
for (int i = 0, imax = transforms.Length; i < imax; ++i) { 
     Transform t = transforms[i]; 
     t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver); 
}

13)音效的播放

 先添加Auido Source, 设置Audio Clip, 也可以在代码中加入。然后在代码中调用audio.Play(), 参考如下代码:

1
2
3
4
5
6
7
8
public AudioClip aClip;
...
void Start () {
     ...
     audio.clip = aClips;
     audio.Play();
     ...
}

另外,如果是3d音效的话,需要调整audio Souce中的panLevel才能听到声音,不清楚原因。

14)调试技巧

可以在OnDrawGizmos函数来进行矩形区域等,达到调试的目的,请参考NGUI中的UIDraggablePanel.cs文件中的那个函数实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#if UNITY_EDITOR
     /// <summary>
     /// Draw a visible orange outline of the bounds.
     /// </summary>
     void OnDrawGizmos ()
     {
         if (mPanel != null )
         {
             Bounds b = bounds;
             Gizmos.matrix = transform.localToWorldMatrix;
             Gizmos.color = new Color(1f, 0.4f, 0f);
             Gizmos.DrawWireCube( new Vector3(b.center.x, b.center.y, b.min.z), new Vector3(b.size.x, b.size.y, 0f));
         }
     }
#endif
15)延时相关( StartCoroutine)
1
2
3
4
5
6
7
8
StartCoroutine(DestoryPlayer());
...
IEnumerator DestoryPlayer() {
     Instantiate(explosionPrefab, transform.position, transform.rotation);
     gameObject.renderer.enabled = false ;
     yield return new WaitForSeconds(1.5f);
     gameObject.renderer.enabled = true ;
}
16)Random做种子
1
Random.seed = System.Environment.TickCount;
17) 调试技巧,可以把值方便地在界面上打印出来
1
2
3
void OnGUI() {
     GUILayout.Label( "deltaTime is: " + Time.deltaTime);
}

你可能感兴趣的:(unity,技巧,AnYuanLzh)