【Unity】技巧集合

转发,请保持地址:http://blog.csdn.net/stalendp/article/details/17114135

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

1)保存运行中的状态

unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在 “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。(其实这个拷贝过程是序列化过程,这种方法是序列化到内存中;另外一种方法就是序列化到磁盘上,即把内容拖动到文件夹中变成prefab,效果也是一样的)

2)Layer的用法

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

3D Raycast

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. RaycastHit hit;  
  2. if(Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, (1<<LayerMask.NameToLayer("Ground")))) {  
  3. ...  
  4. }  

2D Raycast

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Collider2D h = Physics2D.OverlapPoint(cam2d.ScreenToWorldPoint(Input.mousePosition), (1<<LayerMask.NameToLayer("xxx")));  
  2. if(h) {  
  3. ...  
  4. }  

3)物理摄像头取色(WebCamTexture)

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Texture2D exactCamData() {  
  2.     // get the sample pixels  
  3.     Texture2D snap = new Texture2D((int)detectSize.x, (int)detectSize.y);  
  4.     snap.SetPixels(webcamTexture.GetPixels((int)detectStart.x, (int)detectStart.y, (int)detectSize.x, (int)detectSize.y));  
  5.     snap.Apply();  
  6.     return snap;  
  7. }  

保存截图:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. System.IO.File.WriteAllBytes(Application.dataPath + "/test.png", exactCamData().EncodeToPNG());  

4) 操作componenent

添加:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. CircleCollider2D cld = (CircleCollider2D)colorYuan[i].AddComponent(typeof(CircleCollider2D));  
  2. cld.radius = 1;  

删除:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Destroy(transform.gameObject.GetComponent<SpriteRenderer>());  

5)动画相关


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

触发fsShake:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void Awake() {  
  2.     anims = new Animator[(int)FColorType.ColorNum];  
  3. }  
  4. ....  
  5. if(needShake) {  
  6.     curAnim.SetTrigger("shake");  
  7. }  

关闭fsShake

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void Update() {  
  2. ....  
  3. if(curAnim) {  
  4.     AnimatorStateInfo stateInfo = curAnim.GetCurrentAnimatorStateInfo(0);  
  5.     if(stateInfo.nameHash == Animator.StringToHash("Base Layer.fsShake")) {  
  6.         curAnim.SetBool("shake"false);  
  7.         curAnim = null;  
  8.         print ("======>>>>> stop shake!!!!");  
  9.     }  
  10. }  
  11. ....  
  12. }  

关于Animator.StringToHash函数的说明:

animator的setBool,setTrigger等函数都有两种参数形式,一个接收string,一个接收hash;其实Animator内部是使用hash来记录相应信息的,所以接收string类型的函数内部会帮你调用StringToHash这个函数;所以如果要经常调用setTrigger等,请把参数名称hash化保持以便反复使用,从而提高性能


在状态机animator中获取animation state 和animation clip的方法(参考http://answers.unity3d.com/questions/692593/get-animation-clip-length-using-animator.html):

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static AnimationClip getAnimationClip(Animator anim, string clipName) {  
  2.     UnityEditorInternal.State state = getAnimationState(anim, clipName);  
  3.     return state!=null ? state.GetMotion() as AnimationClip : null;  
  4. }  
  5.   
  6. public static UnityEditorInternal.State getAnimationState(Animator anim, string clipName) {  
  7.     UnityEditorInternal.State state = null;  
  8.     if(anim != null) {  
  9.         UnityEditorInternal.AnimatorController ac = anim.runtimeAnimatorController as UnityEditorInternal.AnimatorController;  
  10.         UnityEditorInternal.StateMachine sm = ac.GetLayer(0).stateMachine;  
  11.           
  12.         for(int i = 0; i < sm.stateCount; i++) {  
  13.             UnityEditorInternal.State _state = sm.GetState(i);  
  14.             if(state.uniqueName.EndsWith("." + clipName)) {  
  15.                 state = _state;  
  16.             }  
  17.         }  
  18.     }  
  19.     return state;  
  20. }  

6)scene的切换

同步方式:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Application.LoadLevel(currentName);  

异步方式:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Application.LoadLevelAsync("ARScene");  

7)加载资源

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. transform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);  
10)保存数据

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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) 遍历子对象

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Transform[] transforms = target.GetComponentsInChildren<Transform>();  
  2. for (int i = 0, imax = transforms.Length; i < imax; ++i) {  
  3.     Transform t = transforms[i];  
  4.     t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);  
  5. }  

13)音效的播放

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

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public AudioClip aClip;  
  2. ...  
  3. void Start () {   
  4.     ...  
  5.     audio.clip = aClips;  
  6.     audio.Play();  
  7.     ...  
  8. }  

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

14)调试技巧(Debug)

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

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #if UNITY_EDITOR  
  2.     /// <summary>  
  3.     /// Draw a visible orange outline of the bounds.  
  4.     /// </summary>  
  5.     void OnDrawGizmos ()  
  6.     {  
  7.         if (mPanel != null)  
  8.         {  
  9.             Bounds b = bounds;  
  10.             Gizmos.matrix = transform.localToWorldMatrix;  
  11.             Gizmos.color = new Color(1f, 0.4f, 0f);  
  12.             Gizmos.DrawWireCube(new Vector3(b.center.x, b.center.y, b.min.z), new Vector3(b.size.x, b.size.y, 0f));  
  13.         }  
  14.     }  
  15. #endif  

15)延时相关( StartCoroutine)

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. StartCoroutine(DestoryPlayer());  
  2. ...  
  3. IEnumerator DestoryPlayer() {  
  4.     Instantiate(explosionPrefab, transform.position, transform.rotation);  
  5.     gameObject.renderer.enabled = false;  
  6.     yield return new WaitForSeconds(1.5f);  
  7.     gameObject.renderer.enabled = true;  
  8. }  

16)Random做种子

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Random.seed = System.Environment.TickCount;   
  2. 或者  
  3. Random.seed = System.DateTime.Today.Millisecond;  

17) 调试技巧(debug),可以把值方便地在界面上打印出来

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void OnGUI() {  
  2.     GUI.contentColor = Color.green;  
  3.     GUILayout.Label("deltaTime is: " + Time.deltaTime);  
  4. }  

18)分发消息

sendMessage, BroadcastMessage等

19) 游戏暂停(对timeScale进行设置)

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Time.timeScale = 0;  

20) 实例化一个prefab

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Rigidbody2D propInstance = Instantiate(backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;  

21)Lerp函数的使用场景

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Set the health bar's colour to proportion of the way between green and red based on the player's health.  
  2. healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);  

22)在特定位置播放声音

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Play the bomb laying sound.  
  2. AudioSource.PlayClipAtPoint(bombsAway,transform.position);  

23) 浮点数相等的判断(由于浮点数有误差, 所以判断的时候最好不要用等号,尤其是计算出来的结果)

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (Mathf.Approximately(1.0, 10.0/10.0))  
  2.     print ("same");  

24)通过脚本修改shader中uniform的值

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //shader的写法  
  2. Properties {  
  3.     ...  
  4.     disHeight ("threshold distance", Float) = 3  
  5. }  
  6.    
  7. SubShader {  
  8.     Pass {  
  9.         CGPROGRAM  
  10.         #pragma vertex vert    
  11.         #pragma fragment frag   
  12.         ...  
  13.         uniform float disHeight;  
  14.         ...   
  15. // ===================================  
  16. // 修改shader中的disHeight的值  
  17. gameObject.renderer.sharedMaterial.SetFloat("disHeight", height);  

25) 获取当前level的名称

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Application.loadedLevelName  

26)双击事件

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void OnGUI() {  
  2.     Event Mouse = Event.current;  
  3.     if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) {  
  4.         print("Double Click");  
  5.     }  
  6. }  

27) 日期:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. System.DateTime dd = System.DateTime.Now;  
  2. GUILayout.Label(dd.ToString("M/d/yyyy"));  

28)  RootAnimation中移动的脚本处理

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class RootControl : MonoBehaviour {  
  2.     void OnAnimatorMove() {  
  3.         Animator anim = GetComponent<Animator>();  
  4.         if(anim) {  
  5.             Vector3 newPos = transform.position;  
  6.             newPos.z += anim.GetFloat("Runspeed") * Time.deltaTime;  
  7.             transform.position = newPos;  
  8.         }  
  9.     }  
  10. }  

29) BillBoard效果(广告牌效果,或者向日葵效果,使得对象重视面向摄像机)

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class BillBoard : MonoBehaviour {  
  2.     // Update is called once per frame  
  3.     void Update () {  
  4.         transform.LookAt(Camera.main.transform.position, -Vector3.up);  
  5.     }  
  6. }  

30)script中的属性编辑器(Property Drawers),还可以自定义属性编辑器

参考: http://blogs.unity3d.com/2012/09/07/property-drawers-in-unity-4/

http://docs.unity3d.com/Manual/editor-PropertyDrawers.html

其中Popup好像无效,但是enum类型的变量,能够达到Popup的效果

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class Example : MonoBehaviour {  
  2.     public string playerName = "Unnamed";  
  3.   
  4.     [Multiline]  
  5.     public string playerBiography = "Please enter your biography";  
  6.   
  7.     [Popup ("Warrior""Mage""Archer""Ninja")]  
  8.     public string @class = "Warrior";  
  9.   
  10.     [Popup ("Human/Local""Human/Network""AI/Easy""AI/Normal""AI/Hard")]  
  11.     public string controller;  
  12.   
  13.     [Range (0, 100)]  
  14.     public float health = 100;  
  15.   
  16.     [Regex (@"^(?:\d{1,3}\.){3}\d{1,3}$""Invalid IP address!\nExample: '127.0.0.1'")]  
  17.     public string serverAddress = "192.168.0.1";  
  18.   
  19.     [Compact]  
  20.     public Vector3 forward = Vector3.forward;  
  21.   
  22.     [Compact]  
  23.     public Vector3 target = new Vector3 (100, 200, 300);  
  24.   
  25.     public ScaledCurve range;  
  26.     public ScaledCurve falloff;  
  27.   
  28.     [Angle]  
  29.     public float turnRate = (Mathf.PI / 3) * 2;  
  30. }  

31)Mobile下面使用lightmapping问题的解决方案

在mobile模式下,lightmapping可能没有反应,可以尝试使用mobile下的shader,可以解决问题。更多请参考:http://forum.unity3d.com/threads/138978-Lightmap-problem-in-iPhone

32) Unity下画线的功能(用于debug)

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Debug.DrawLine (Vector3.zero, new Vector3 (10, 0, 0), Color.red);  

33)Shader中代码的复用(CGINCLUDE的使用)

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Shader "Self-Illumin/AngryBots/InterlacePatternAdditive" {  
  2.     Properties {  
  3.         _MainTex ("Base", 2D) = "white" {}  
  4.         //...  
  5.     }  
  6.       
  7.     CGINCLUDE  
  8.   
  9.         #include "UnityCG.cginc"  
  10.   
  11.         sampler2D _MainTex;  
  12.         //...                 
  13.                           
  14.         struct v2f {  
  15.             half4 pos : SV_POSITION;  
  16.             half2 uv : TEXCOORD0;  
  17.             half2 uv2 : TEXCOORD1;  
  18.         };  
  19.   
  20.         v2f vert(appdata_full v) {  
  21.             v2f o;  
  22.             // ...  
  23.             return o;   
  24.         }  
  25.           
  26.         fixed4 frag( v2f i ) : COLOR {    
  27.             // ...  
  28.             return colorTex;  
  29.         }  
  30.       
  31.     ENDCG  
  32.       
  33.     SubShader {  
  34.         Tags {"RenderType" = "Transparent" "Queue" = "Transparent" "Reflection" = "RenderReflectionTransparentAdd" }  
  35.         Cull Off  
  36.         ZWrite Off  
  37.         Blend One One  
  38.           
  39.     Pass {  
  40.       
  41.         CGPROGRAM  
  42.           
  43.         #pragma vertex vert  
  44.         #pragma fragment frag  
  45.         #pragma fragmentoption ARB_precision_hint_fastest   
  46.           
  47.         ENDCG  
  48.            
  49.         }  
  50.                   
  51.     }   
  52.     FallBack Off  
  53. }  

34)获取AnimationCurve的时长

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. _curve.keys[_curve.length-1].time;  

35)C#中string转变成byte[]:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);  
  2. byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);  
  3. System.Text.Encoding.Default.GetBytes(sPara)  
  4. new ASCIIEncoding().GetBytes(cpara);  
  5. char[] cpara=new char[bpara.length];  
  6. for(int i=0;i <bpara.length;i ++){char[i]=system.convert.tochar(bpara[i]);}     

36) 排序

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. list.Sort(delegate(Object a, Object b) { return a.name.CompareTo(b.name); });  

37) NGUI的相关类关系:




38)使得脚本能够在editor中实时反映:

在脚本前加上:[ExecuteInEditMode], 参考UISprite。

39)隐藏相关属性

属性前加上 [HideInInspector],在shader中也适用;

比如:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class ResourceLoad : MonoBehaviour {  
  2.     [HideInInspector] public string ressName = "Sphere";  
  3.     public string baseUrl = "http://192.168.56.101/ResUpdate/{0}.assetbundle";  
[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Shader "stalendp/imageShine" {  
  2.     Properties {  
  3.         [HideInInspector] _image ("image", 2D) = "white" {}  
  4.         _percent ("_percent", Range(-5, 5)) = 1  
  5.         _angle("_angle", Range(0, 1)) = 0  
  6.     }  

40)属性的序列化

可被序列化的属性,可以显示在Inspector面板上(可以使用HideInInspector来隐藏);public属性默认是可被序列化的,private默认是不可序列化的。使得private属性可被序列化,可以使用[SerializeField]来修饰。如下:

[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. [SerializeField] private string ressName = "Sphere";  

41)Shader编译的多样化(Making multiple shader program variants

shader通常如下的写法:

#pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON
这样可以把Shader编译成多个版本。使用的时候,局部设置Material.EnableKeyword, DisableKeyword;或则 全局设置Shader.EnableKeyword and DisableKeyword进行设置。
42)多个scene共享内容

 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1.  void Awake() {  
  2.     DontDestroyOnLoad(transform.gameObject);  
  3. }  
43) 使用Animation播放unity制作的AnimationClip:
首先需要设置AnimationType的类型为1 (需要在animationClip的Debug模式的属性中进行设置,如下图。另外,如果需要在animator中播放动画,需要类型为2);

代码如下:
 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. string clipName = "currentClip";  
  2. AnimationClip clip = ...;  
  3. // 设置animationClip  
  4. if (anim == null) {  
  5.     anim = gameObject.AddComponent<Animation>();  
  6. }  
  7. anim.AddClip(clip, clipName);  
  8. anim[clipName].speed = _speedScale;  
  9. // 计算时间  
  10. float duration = anim[clipName].length;  
  11. duration /= _speedScale;  
  12. // 播放动画  
  13. anim.Play(clipName);  
  14. yield return new WaitForSeconds(duration + 0.1f);  
  15. // 动画结束动作  
  16. anim.Stop();  
  17. anim.RemoveClip(clipName);  
44) RenderTexture的全屏效果
cs端:
 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. MeshFilter mesh = quard.GetComponent<MeshFilter> ();  
  2. // 创建和摄像机相关的renderTexture  
  3. RenderTexture rTex = new RenderTexture ((int)cam.pixelWidth, (int)cam.pixelHeight, 16);  
  4. cam.targetTexture = rTex;  
  5. mesh.renderer.material.mainTexture = rTex;  
shader端:
 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include "UnityCG.cginc"             
  2. sampler2D _MainTex;  
  3. sampler2D _NoiseTex;  
  4.       
  5. struct v2f {      
  6.     half4 pos:SV_POSITION;      
  7.     half2 uv : TEXCOORD0;   
  8.     float4 srcPos: TEXCOORD1;    
  9. };    
  10.   
  11. v2f vert(appdata_full v) {    
  12.     v2f o;    
  13.     o.pos = mul (UNITY_MATRIX_MVP, v.vertex);    
  14.     o.uv = v.texcoord.xy;  
  15.     o.srcPos = ComputeScreenPos(o.pos);  
  16.     return o;    
  17. }    
  18.   
  19. fixed4 frag(v2f i) : COLOR0 {  
  20.     float tmp = saturate(1-(length(i.uv-float2(0.5,0.5)))*2)*0.04;            
  21.     float2 wcoord = (i.srcPos.xy/i.srcPos.w) + tex2D(_NoiseTex, i.uv) * tmp - tmp/2;  
  22.     return tex2D(_MainTex, wcoord);  
  23. }    
45)使用RenderTexture制作屏幕特效:
 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. [ExecuteInEditMode]  
  2. public class MyScreenEffect : MonoBehaviour {  
  3.     ...  
  4.     void OnRenderImage(RenderTexture source, RenderTexture dest) {  
  5.         Graphics.Blit(source, dest, material);  
  6.     }  
  7. }  
如果需要多次渲染,需要使用RenderTexture.GetTemporary生成临时的RenderTexture,这个方法会从unity维护的池中获取,所以在使用完RenderTexture后,尽快调用RenderTexture.ReleaseTemporary使之返回池中。 RenderTexture存在于GPU的DRAM中,具体实现可以参考Cocos2dx中的写法来理解(CCRenderTexture.cpp中有具体实现)。GPU的架构请参考:http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter30.html
46) 特定条件下暂停unity
在调试战斗的时候,需要在特定条件下暂停unity,以便查看一些对象的设置。可以使用Debug.Break();来达到目的。这是需要处于debug模式,才能够达到效果。
47)在特定exception发生时暂停执行;
默认情况下,unity在遇到异常时,是不会停止执行的。但是如果要在nullReferenceException等exception发生时,进行调试。可以在MonoDevelop的菜单中选择Run/Exceptions..., 做相关设置:

48)NGUI性能建议
相关知识:1)在NGUI中,一个Panel对应一个DrawCall(当然一个panel里面的UISprite来自多个图集,就会有多个drawCall);2)当一个UISprite等UIWidget控件的active改变时,DrawCall会重新计算一遍;3)DrawCall的计算比较耗时,首先会收集DrawCall下所有UIWidget的verts,norms,trans,uvs,cols等信息,还要向GPU传输数据,相对比较耗时。
问题:当在一个Panel中有大量的UIWidget,有一部分是经常改变active的,有些部分则不怎么变。这样就会导致频繁地计算DrawCall。
性能提升方案:把经常改变active的控件单独到一个panel中。把不怎么变动的部分独立到另外的panel中。
 
49)NGUI中设置自定义的Shader,并改变properties的值。
使用UITexture,可以设置自定义的Material。需要注意的是,改变properties的值,需要使用UITexture中的drawCall的dynamicMaterial,如下:
 
 
  1. UITexture tex=....;  
  2. tex.drawCall.dynamicMaterial.SetFloat("_percent", du/DU);  
50) 鉴别unity中的InputTouch的类型:
 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public enum OperateStatus {  
  2.     OS_Idle=0,  
  3.     OS_Draging=1,  
  4.     OS_Scaling=2  
  5. }  
  6. .....  
  7.   
  8. void Update () {  
  9.    ......  
  10.        TouchPhase tp = Input.GetTouch(0).phase;  
  11.     if(tp==TouchPhase.Ended || tp==TouchPhase.Canceled) {  
  12.         oStatus = OperateStatus.OS_Idle;  
  13.     } else {  
  14.         oStatus = Input.touchCount>1 ? OperateStatus.OS_Scaling : OperateStatus.OS_Draging;  
  15.     }  
  16. .....  
  17. }  
51) 物理系统的性能提示:
Unity中涉及物理模拟的有静态碰撞(static collider)和动态碰撞(dynamic collider)。其中,静态碰撞物体是指具有collider属性但没有rigidbody的物体,动态碰撞物体是指具有collider和rigidbody属性的物体。
Unity引擎期待静态物体是静止,会把场景中的所有静态物体统一计算成一个叫static collider cache的东西来加速物理模拟。但是如果其中某个静态物体进行了移动,系统就要重新计算static collider cache;而这个代价是很大的。所以如果一个物体是要经常移动的,应该设计成动态物体,即添加rigidbody成分;至于使rigidbody不响应重力等作用力的影响,请参考rigidbody中的"Use Gravity"和“Is Kinematic”属性。
如果rigidbody是kinematic的,它不响应force,可以用来制作飞行障碍物等效果。如果不是kinematic的,就会响应foce。
参考如下官方教程最后的性能分析:http://unity3d.com/learn/tutorials/projects/roll-a-ball/collecting-and-counting
52) unity中四种Collider的对比:
 
 
类型能否移动是否接收Trigger消息是否受碰撞影响是否受物理影响
Static代价大NoNoNo
Kinematic RigidbodyYesYesNoNo
Character ControllerYes未知YesNo
RigidbodyYesYesYesYes
仔细观察上面的表格,发现越往下,特性越多。官方在介绍collision的时候,没有加入讨论Character Controller,这个是我自己添加比较的。
另外,如果一个物体能够受碰撞影响,当然就能够接收Collition消息了。
关于接收Collision消息和Trigger消息的官方的详细表,请参考http://docs.unity3d.com/Manual/CollidersOverview.html 的文末的表格。

53) 使一个物体依附在一个表面上,保持物体的up方向和表面的法线方向一致(物体记为obj,表面记为suf):
方法1:
  
  
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. obj.transform.rotation = Quaternion.FromToRotation(obj.transform.up, suf.transform.up)* obj.transform.rotation;  
方法2:
   
   
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Vector3 axis = Vector3.Cross(obj.transform.up, suf.transform.up);  
  2. float angle = Vector3.Angle(obj.transform.up, suf.transform.up);  
  3. obj.transform.Rotate(axis, angle, Space.World);  
54)AngryBots中的showFPS代码:
 
 
[javascript] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @script ExecuteInEditMode  
  2.   
  3. private var gui : GUIText;  
  4.   
  5. private var updateInterval = 1.0;  
  6. private var lastInterval : double// Last interval end time  
  7. private var frames = 0; // Frames over current interval  
  8.   
  9. function Start()  
  10. {  
  11.     lastInterval = Time.realtimeSinceStartup;  
  12.     frames = 0;  
  13. }  
  14.   
  15. function OnDisable ()  
  16. {  
  17.     if (gui)  
  18.         DestroyImmediate (gui.gameObject);  
  19. }  
  20.   
  21. function Update()  
  22. {  
  23. #if !UNITY_FLASH  
  24.     ++frames;  
  25.     var timeNow = Time.realtimeSinceStartup;  
  26.     if (timeNow > lastInterval + updateInterval)  
  27.     {  
  28.         if (!gui)  
  29.         {  
  30.             var go : GameObject = new GameObject("FPS Display", GUIText);  
  31.             go.hideFlags = HideFlags.HideAndDontSave;  
  32.             go.transform.position = Vector3(0,0,0);  
  33.             gui = go.guiText;  
  34.             gui.pixelOffset = Vector2(5,55);  
  35.         }  
  36.         var fps : float = frames / (timeNow - lastInterval);  
  37.         var ms : float = 1000.0f / Mathf.Max (fps, 0.00001);  
  38.         gui.text = ms.ToString("f1") + "ms " + fps.ToString("f2") + "FPS";  
  39.         frames = 0;  
  40.         lastInterval = timeNow;  
  41.     }  
  42. #endif  
  43. }  
55)关于Hierarchy中按名称的字母排序功能:
 
 
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class AlphaNumericSort : BaseHierarchySort  
  2. {  
  3.     public override int Compare(GameObject lhs, GameObject rhs)  
  4.     {  
  5.         if (lhs == rhs) return 0;  
  6.         if (lhs == nullreturn -1;  
  7.         if (rhs == nullreturn 1;  
  8.   
  9.         return EditorUtility.NaturalCompare(lhs.name, rhs.name);  
  10.     }  
  11. }  
把上面的代码放到工程中之后,在Hierarchy中就会出现排序的按钮,如下:

BaseHierarchySort的官方地址:http://docs.unity3d.com/ScriptReference/BaseHierarchySort.html
56)用脚本在Mac下打开多个Unity工程:
默认到情况下,Mac中只能够允许一个Unity实例。但是通过脚本(把工程路径写到Unity启动参数中)可以方便地打开多个常用的工程(参考:Open Multiple Unity Projects Simultaneously
 
 
[python] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #!/bin/bash  
  2. /Applications/Unity/Unity.app/Contents/MacOS/Unity -projectPath "/path/to/your/projectA"  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值