unity3d小技巧合集.doc_第1页
unity3d小技巧合集.doc_第2页
unity3d小技巧合集.doc_第3页
unity3d小技巧合集.doc_第4页
unity3d小技巧合集.doc_第5页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

【Unity】技巧集合转发,请保持地址:/stalendp/article/details/17114135这篇文章将收集unity的相关技巧,会不断地更新内容。1)保存运行中的状态unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在 “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。2)Layer的用法LayerMask.NameToLayer(Ground); / 通过名字获取layer3D Raycastcsharpview plaincopy1. RaycastHithit;2. if(Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition),outhit,Mathf.Infinity,(1LayerMask.NameToLayer(Ground)3. .4. 2D Raycastcsharpview plaincopy1. Collider2Dh=Physics2D.OverlapPoint(cam2d.ScreenToWorldPoint(Input.mousePosition),(1LayerMask.NameToLayer(xxx);2. if(h)3. .4. 3)物理摄像头取色(WebCamTexture)csharpview plaincopy1. Texture2DexactCamData()2. /getthesamplepixels3. Texture2Dsnap=newTexture2D(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. returnsnap;7. 保存截图:csharpview plaincopy1. System.IO.File.WriteAllBytes(Application.dataPath+/test.png,exactCamData().EncodeToPNG();4) 操作componenent添加:csharpview plaincopy1. CircleCollider2Dcld=(CircleCollider2D)colorYuani.AddComponent(typeof(CircleCollider2D);2. cld.radius=1;删除:csharpview plaincopy1. Destroy(transform.gameObject.GetComponent();5)动画相关状态Init到状态fsShake的的条件为:参数shaketrue;代码中的写法:触发fsShake:csharpview plaincopy1. voidAwake()2. anims=newAnimator(int)FColorType.ColorNum;3. 4. .5. if(needShake)6. curAnim.SetTrigger(shake);7. 关闭fsShakecsharpview plaincopy1. voidUpdate()2. .3. if(curAnim)4. AnimatorStateInfostateInfo=curAnim.GetCurrentAnimatorStateInfo(0);5. if(stateIHash=Animator.StringToHash(BaseLayer.fsShake)6. curAnim.SetBool(shake,false);7. curAnim=null;8. print(=stopshake!);9. 10. 11. .12. 6)scene的切换同步方式:csharpview plaincopy1. Application.LoadLevel(currentName);异步方式:csharpview plaincopy1. Application.LoadLevelAsync(ARScene);7)加载资源csharpview plaincopy1. Resources.Load(string.Format(01:D2,mPrefix,5);8)Tag VS. Layer Tag用来查询对象 Layer用来确定哪些物体可以被raycast,还有用在camera render中9)旋转transform.eulerAngles 可以访问 rotate的 xyzcsharpview plaincopy1. transform.RotateAround(pivotTransVector,Vector3.up,-0.5f*(tmp-preX)*speed);10)保存数据csharpview plaincopy1. PlayerPrefs.SetInt(isInit_+Application.loadedLevelName,1);11)动画编码/lopezycj/archive/2012/05/18/Unity3d_AnimationEvent.html/Components/animeditor-AnimationEvents.html/questions/8172/how-to-add-new-curves-or-animation-events-to-an-im.html12) 遍历子对象csharpview plaincopy1. Transformtransforms=target.GetComponentsInChildren();2. for(inti=0,imax=transforms.Length;iimax;+i)3. Transformt=transformsi;4. t.gameObject.SendMessage(functionName,gameObject,SendMessageOptions.DontRequireReceiver);5. 13)音效的播放先添加Auido Source, 设置Audio Clip, 也可以在代码中加入。然后在代码中调用audio.Play(), 参考如下代码:csharpview plaincopy1. publicAudioClipaClip;2. .3. voidStart()4. .5. audio.clip=aClips;6. audio.Play();7. .8. 另外,如果是3d音效的话,需要调整audio Souce中的panLevel才能听到声音,不清楚原因。14)调试技巧(Debug)可以在OnDrawGizmos函数来进行矩形区域等,达到调试的目的,请参考NGUI中的UIDraggablePanel.cs文件中的那个函数实现。csharpview plaincopy1. #ifUNITY_EDITOR2. /3. /Drawavisibleorangeoutlineofthebounds.4. /5. voidOnDrawGizmos()6. 7. if(mPanel!=null)8. 9. Boundsb=bounds;10. Gizmos.matrix=transform.localToWorldMatrix;11. Gizmos.color=newColor(1f,0.4f,0f);12. Gizmos.DrawWireCube(newVector3(b.center.x,b.center.y,b.min.z),newVector3(b.size.x,b.size.y,0f);13. 14. 15. #endif15)延时相关( StartCoroutine)csharpview plaincopy1. StartCoroutine(DestoryPlayer();2. .3. IEnumeratorDestoryPlayer()4. Instantiate(explosionPrefab,transform.position,transform.rotation);5. gameObject.renderer.enabled=false;6. yieldreturnnewWaitForSeconds(1.5f);7. gameObject.renderer.enabled=true;8. 16)Random做种子csharpview plaincopy1. Random.seed=System.Environment.TickCount;2. 或者3. Random.seed=System.DateTime.Today.Millisecond;17) 调试技巧(debug),可以把值方便地在界面上打印出来csharpview plaincopy1. voidOnGUI()2. GUILayout.Label(deltaTimeis:+Time.deltaTime);3. 18)分发消息sendMessage,BroadcastMessage等19) 游戏暂停(对timeScale进行设置)csharpview plaincopy1. Time.timeScale=0;20) 实例化一个prefabcsharpview plaincopy1. Rigidbody2DpropInstance=Instantiate(backgroundProp,spawnPos,Quaternion.identity)asRigidbody2D;21)Lerp函数的使用场景csharpview plaincopy1. /Setthehealthbarscolourtoproportionofthewaybetweengreenandredbasedontheplayershealth.2. healthBar.material.color=Color.Lerp(Color.green,Color.red,1-health*0.01f);22)在特定位置播放声音csharpview plaincopy1. /Playthebomblayingsound.2. AudioSource.PlayClipAtPoint(bombsAway,transform.position);23) 浮点数相等的判断(由于浮点数有误差, 所以判断的时候最好不要用等号,尤其是计算出来的结果)csharpview plaincopy1. if(Mathf.Approximately(1.0,10.0/10.0)2. print(same);24)通过脚本修改shader中uniform的值csharpview plaincopy1. /shader的写法2. Properties3. .4. disHeight(thresholddistance,Float)=35. 6. 7. SubShader8. Pass9. CGPROGRAM10. #pragmavertexvert11. #pragmafragmentfrag12. .13. uniformfloatdisHeight;14. .15. /=16. /修改shader中的disHeight的值17. gameObject.renderer.sharedMaterial.SetFloat(disHeight,height);25) 获取当前level的名称csharpview plaincopy1. Application.loadedLevelName26)双击事件csharpview plaincopy1. voidOnGUI()2. EventMouse=Event.current;3. if(Mouse.isMouse&Mouse.type=EventType.MouseDown&Mouse.clickCount=2)4. print(DoubleClick);5. 6. 27) 日期:csharpview plaincopy1. System.DateTimedd=System.DateTime.Now;2. GUILayout.Label(dd.ToString(M/d/yyyy);28) RootAnimation中移动的脚本处理csharpview plaincopy1. classRootControl:MonoBehaviour2. voidOnAnimatorMove()3. Animatoranim=GetComponent();4. if(anim)5. Vector3newPos=transform.position;6. newPos.z+=anim.GetFloat(Runspeed)*Time.deltaTime;7. transform.position=newPos;8. 9. 10. 29) BillBoard效果(广告牌效果,或者向日葵效果,使得对象重视面向摄像机)csharpview plaincopy1. publicclassBillBoard:MonoBehaviour2. /Updateiscalledonceperframe3. voidUpdate()4. transform.LookAt(Camera.main.transform.position,Vector3.up);5. 6. 30)script中的属性编辑器(Property Drawers),还可以自定义属性编辑器参考:/2012/09/07/property-drawers-in-unity-4/其中Popup好像无效,但是enum类型的变量,能够达到Popup的效果csharpview plaincopy1. publicclassExample:MonoBehaviour2. publicstringplayerName=Unnamed;3. 4. Multiline5. publicstringplayerBiography=Pleaseenteryourbiography;6. 7. Popup(Warrior,Mage,Archer,Ninja)8. publicstringclass=Warrior;9. 10. Popup(Human/Local,Human/Network,AI/Easy,AI/Normal,AI/Hard)11. publicstringcontroller;12. 13. Range(0,100)14. publicfloathealth=100;15. 16. Regex(?:d1,3.)3d1,3$,InvalidIPaddress!nExample:)17. publicstringserverAddress=;18. 19. Compact20. publicVector3forward=Vector3.forward;21. 22. Compact23. publicVector3target=newVector3(100,200,300);24. 25. publicScaledCurverange;26. publicScaledCurvefalloff;27. 28. Angle29. publicfloatturnRate=(Mathf.PI/3)*2;30. 31)Mobile下面使用lightmapping问题的解决方案在mobile模式下,lightmapping可能没有反应,可以尝试使用mobile下的shader,可以解决问题。更多请参考:/threads/138978-Lightmap-problem-in-iPhone32) Unity下画线的功能(用于debug)csharpview plaincopy1. Debug.DrawLine(Vector3.zero,newVector3(10,0,0),Color.red);33)Shader中代码的复用(CGINCLUDE的使用)cppview plaincopy1. ShaderSelf-Illumin/AngryBots/InterlacePatternAdditive2. Properties3. _MainTex(Base,2D)=white4. /.5. 6. 7. CGINCLUDE8. 9. #includeUnityCG.cginc10. 11. sampler2D_MainTex;12. /.13. 14. structv2f15. half4pos:SV_POSITION;16. half2uv:TEXCOORD0;17. half2uv2:TEXCOORD1;18. ;19. 20. v2fvert(appdata_fullv)21. v2fo;22. /.23. returno;24. 25. 26. fixed4frag(v2fi):COLOR27. /.28. returncolorTex;29. 30. 31. ENDCG32. 33. SubShader34. TagsRenderType=TransparentQueue=TransparentReflection=RenderReflectionTransparentAdd35. CullOff36. ZWriteOff37. BlendOneOne38. 39. Pass40. 41. CGPROGRAM42. 43. #pragmavertexvert44. #pragmafragmentfrag45. #pragmafragmentoptionARB_precision_hint_fastest46. 47. ENDCG48. 49. 50. 51. 52. FallBackOff53. 34)获取AnimationCurve的时长csharpview plaincopy1. _curve.keys_curve.length-1.time;35)C#中string转变成byte:csharpview plaincopy1. byteb1=System.Text.Encoding.UTF8.GetBytes(myString);2. byteb2=System.Text.Encoding.ASCII.GetBytes(myString);3. System.Text.Encoding.Default.GetBytes(sPara)4. newASCIIEncoding().GetBytes(cpara);5. charcpara=newcharbpara.length;6. for(inti=0;ibpara.length;i+)chari=system.convert.tochar(bparai);36) 排序csharpview plaincopy1. list.Sort(delegate(Objecta,Objectb).CompareTo(););37) NGUI的相关类关系:38)使得脚本能够在editor中实时反映:在脚本前加上:ExecuteInEditMode, 参考UISprite。39)隐藏相关属性属性前加上 HideInInspector,在shader中也适用;比如:csharpview plaincopy1. publicclassResourceLoad:MonoBehaviour2. HideInInspectorpublicstringressName=Sphere;3. publicstringbaseUrl=01/ResUpdate/0.assetbundle;csharpview plaincopy1. Shaderstalendp/imageShine2. Properties3. HideInInspector_image(image,2D)=white4. _percent(_percent,Range(-5,5)=15. _angle(_angle,Range(0,1)=06. 40)属性的序列化可被序列化的属性,可以显示在Inspector面板上(可以使用HideInInspector来隐藏);public属性默认是可被序列化的,private默认是不可序列化的。使得private属性可被序列化,可以使用SerializeField来修饰。如下:csharpview plaincopy1. SerializeFieldprivatestringressName=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 plaincopy1. voidAwake()2. DontDestroyOnLoad(transform.gameObject);3. 43) 使用Animation播放unity制作的AnimationClip:首先需要设置AnimationType的类型为1 (需要在animationClip的Debug模式的属性中进行设置,如下图。另外,如果需要在animator中播放动画,需要类型为2);代码如下:csharp view plaincopy1. stringclipName=currentClip;2. AnimationClipclip=.;3. /设置animationClip4. if(anim=null)5. anim=gameObject.AddComponent();6. 7. anim.AddClip(clip,clipName);8. animclipName.speed=_speedScale;9. /计算时间10. floatduration=animclipName.length;11. duration/=_speedScale;12. /播放动画13. anim.Play(clipName);14. yieldreturnnewWaitForSeconds(duration+0.1f);15. /动画结束动作16. anim.Stop();17. anim.RemoveClip(clipName);44) RenderTexture的全屏效果cs端:csharp view plaincopy1. MeshFiltermesh=quard.GetComponent();2. /创建和摄像机相关的renderTexture3. RenderTexturerTex=newRenderTexture(int)cam.pixelWidth,(int)cam.pixelHeight,16);4. cam.targetTexture=rTex;5. mesh.renderer.material.mainTexture=rTex;shader端:csharp view plaincopy1. #includeUnityCG.cginc2. sampler2D_MainTex;3. sampler2D_NoiseTex;4. 5. structv2f6. half4pos:SV_POSITION;7. half2uv:TEXCOORD0;8. float4srcPos:TEXCOORD1;9. ;10. 11. v2fvert(appdata_fullv)12. v2fo;13. o.pos=mul(UNITY_MATRIX_MVP,v.vertex);14. o.uv=v.texcoord.xy;15. o.srcPos=ComputeScreenPos(o.pos);16. returno;17. 18. 19. fixed4frag(v2fi):COLOR020. floattmp=saturate(1-(length(i.uv-float2(0.5,0.5)*2)*0.04;21. float2wcoord=(i.srcPos.xy/i.srcPos.w)+tex2D(_NoiseTex,i.uv)*tmp-tmp/2;22. returntex2D(_MainTex,wcoord);23. 45)使用RenderTexture制作屏幕特效:csharp view plaincopy1. ExecuteInEditMode2. publicclassMyScreenEffect:MonoBehaviour3. .4. voidOnRenderImage(RenderTextu

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论