首页 unity3d小技巧合集

unity3d小技巧合集

举报
开通vip

unity3d小技巧合集 HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"【Unity】技巧集合转发,请保持地址:HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\t"_blank"http://blog.csdn.net/stalendp/article/details/17114135这篇文章将收集unity的相关技巧,会不断地更新内容。1)保存运行中的状态un...

unity3d小技巧合集
 HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"【Unity】技巧集合转发,请保持地址:HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\t"_blank"http://blog.csdn.net/stalendp/article/details/17114135这篇文章将收集unity的相关技巧,会不断地更新内容。1)保存运行中的状态unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在“Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。2)Layer的用法LayerMask.NameToLayer("Ground"); //通过名字获取layer3DRaycast[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyRaycastHit hit;  if(Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, (1<());  5)动画相关状态Init到状态fsShake的的条件为:参数shake==true;代码中的写法:触发fsShake:[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyvoid Awake() {      anims = new Animator[(int)FColorType.ColorNum];  }  ....  if(needShake) {      curAnim.SetTrigger("shake");  }  关闭fsShake[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyvoid 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的切换同步方式:[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyApplication.LoadLevel(currentName);  异步方式:[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyApplication.LoadLevelAsync("ARScene");  7)加载资源[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyResources.Load(string.Format("{0}{1:D2}", mPrefix, 5));  8)TagVS.Layer   ->Tag用来查询对象   ->Layer用来确定哪些物体可以被raycast,还有用在camerarender中9)旋转transform.eulerAngles可以访问rotate的xyz[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copytransform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);  10)保存数据[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyPlayerPrefs.SetInt("isInit_" + Application.loadedLevelName, 1);  11)动画编码http://www.cnblogs.com/lopezycj/archive/2012/05/18/Unity3d_AnimationEvent.htmlhttp://game.ceeger.com/Components/animeditor-AnimationEvents.htmlhttp://answers.unity3d.com/questions/8172/how-to-add-new-curves-or-animation-events-to-an-im.html12)遍历子对象[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyTransform[] transforms = target.GetComponentsInChildren();  for (int i = 0, imax = transforms.Length; i < imax; ++i) {      Transform t = transforms[i];      t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);  }  13)音效的播放 先添加AuidoSource,设置AudioClip,也可以在代码中加入。然后在代码中调用audio.Play(),参考如下代码:[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copypublic AudioClip aClip;  ...  void Start () {       ...      audio.clip = aClips;      audio.Play();      ...  }  另外,如果是3d音效的话,需要调整audioSouce中的panLevel才能听到声音,不清楚原因。14)调试技巧(Debug)可以在OnDrawGizmos函数来进行矩形区域等,达到调试的目的,请参考NGUI中的UIDraggablePanel.cs文件中的那个函数实现。[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy#if UNITY_EDITOR      ///       /// Draw a visible orange outline of the bounds.      ///       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)[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyStartCoroutine(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做种子[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyRandom.seed = System.Environment.TickCount;   或者  Random.seed = System.DateTime.Today.Millisecond;  17)调试技巧(debug),可以把值方便地在界面上打印出来[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyvoid OnGUI() {      GUILayout.Label("deltaTime is: " + Time.deltaTime);  }  18)分发消息sendMessage, BroadcastMessage等19)游戏暂停(对timeScale进行设置)[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyTime.timeScale = 0;  20)实例化一个prefab[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyRigidbody2D propInstance = Instantiate(backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;  21)Lerp函数的使用场景[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy// Set the health bar's colour to proportion of the way between green and red based on the player's health.  healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);  22)在特定位置播放声音[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy// Play the bomb laying sound.  AudioSource.PlayClipAtPoint(bombsAway,transform.position);  23)浮点数相等的判断(由于浮点数有误差,所以判断的时候最好不要用等号,尤其是计算出来的结果)[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyif (Mathf.Approximately(1.0, 10.0/10.0))      print ("same");  24)通过脚本修改shader中uniform的值[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy//shader的写法  Properties {      ...      disHeight ("threshold distance", Float) = 3  }     SubShader {      Pass {          CGPROGRAM          #pragma vertex vert            #pragma fragment frag           ...          uniform float disHeight;          ...   // ===================================  // 修改shader中的disHeight的值  gameObject.renderer.sharedMaterial.SetFloat("disHeight", height);  25)获取当前level的名称[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyApplication.loadedLevelName  26)双击事件[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyvoid OnGUI() {      Event Mouse = Event.current;      if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) {          print("Double Click");      }  }  27)日期:[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copySystem.DateTime dd = System.DateTime.Now;  GUILayout.Label(dd.ToString("M/d/yyyy"));  28) RootAnimation中移动的脚本处理[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyclass RootControl : MonoBehaviour {      void OnAnimatorMove() {          Animator anim = GetComponent();          if(anim) {              Vector3 newPos = transform.position;              newPos.z += anim.GetFloat("Runspeed") * Time.deltaTime;              transform.position = newPos;          }      }  }  29)BillBoard效果(广告牌效果,或者向日葵效果,使得对象重视面向摄像机)[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copypublic class BillBoard : MonoBehaviour {      // Update is called once per frame      void Update () {          transform.LookAt(Camera.main.transform.position, Vector3.up);      }  }  30)script中的属性编辑器(PropertyDrawers),还可以自定义属性编辑器参考:HYPERLINK"http://blogs.unity3d.com/2012/09/07/property-drawers-in-unity-4/"\t"_blank" http://blogs.unity3d.com/2012/09/07/property-drawers-in-unity-4/其中Popup好像无效,但是enum类型的变量,能够达到Popup的效果[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copypublic class Example : MonoBehaviour {      public string playerName = "Unnamed";        [Multiline]      public string playerBiography = "Please enter your biography";        [Popup ("Warrior", "Mage", "Archer", "Ninja")]      public string @class = "Warrior";        [Popup ("Human/Local", "Human/Network", "AI/Easy", "AI/Normal", "AI/Hard")]      public string controller;        [Range (0, 100)]      public float health = 100;        [Regex (@"^(?:\d{1,3}\.){3}\d{1,3}$", "Invalid IP address!\nExample: '127.0.0.1'")]      public string serverAddress = "192.168.0.1";        [Compact]      public Vector3 forward = Vector3.forward;        [Compact]      public Vector3 target = new Vector3 (100, 200, 300);        public ScaledCurve range;      public ScaledCurve falloff;        [Angle]      public float turnRate = (Mathf.PI / 3) * 2;  }  31)Mobile下面使用lightmapping问 快递公司问题件快递公司问题件货款处理关于圆的周长面积重点题型关于解方程组的题及答案关于南海问题 的解决 方案 气瓶 现场处置方案 .pdf气瓶 现场处置方案 .doc见习基地管理方案.doc关于群访事件的化解方案建筑工地扬尘治理专项方案下载 在mobile模式下,lightmapping可能没有反应,可以尝试使用mobile下的shader,可以解决问题。更多请参考:HYPERLINK"http://forum.unity3d.com/threads/138978-Lightmap-problem-in-iPhone"\t"_blank"http://forum.unity3d.com/threads/138978-Lightmap-problem-in-iPhone32)Unity下画线的功能(用于debug)[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyDebug.DrawLine (Vector3.zero, new Vector3 (10, 0, 0), Color.red);  33)Shader中代码的复用(CGINCLUDE的使用)[cpp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyShader "Self-Illumin/AngryBots/InterlacePatternAdditive" {      Properties {          _MainTex ("Base", 2D) = "white" {}          //...      }            CGINCLUDE            #include "UnityCG.cginc"            sampler2D _MainTex;          //...                                                   struct v2f {              half4 pos : SV_POSITION;              half2 uv : TEXCOORD0;              half2 uv2 : TEXCOORD1;          };            v2f vert(appdata_full v) {              v2f o;              // ...              return o;           }                    fixed4 frag( v2f i ) : COLOR {                // ...              return colorTex;          }            ENDCG            SubShader {          Tags {"RenderType" = "Transparent" "Queue" = "Transparent" "Reflection" = "RenderReflectionTransparentAdd" }          Cull Off          ZWrite Off          Blend One One                Pass {                CGPROGRAM                    #pragma vertex vert          #pragma fragment frag          #pragma fragmentoption ARB_precision_hint_fastest                     ENDCG                     }                        }       FallBack Off  }  34)获取AnimationCurve的时长[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy_curve.keys[_curve.length-1].time;  35)C#中string转变成byte[]:[csharp] HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copybyte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);  byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);  System.Text.Encoding.Default.GetBytes(sPara)  new ASCIIEncoding().GetBytes(cpara);  char[] cpara=new char[bpara.length];  for(int i=0;i ();  }  anim.AddClip(clip, clipName);  anim[clipName].speed = _speedScale;  // 计算时间  float duration = anim[clipName].length;  duration /= _speedScale;  // 播放动画  anim.Play(clipName);  yield return new WaitForSeconds(duration + 0.1f);  // 动画结束动作  anim.Stop();  anim.RemoveClip(clipName);  44)RenderTexture的全屏效果cs端:[csharp]HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copyMeshFilter mesh = quard.GetComponent ();  // 创建和摄像机相关的renderTexture  RenderTexture rTex = new RenderTexture ((int)cam.pixelWidth, (int)cam.pixelHeight, 16);  cam.targetTexture = rTex;  mesh.renderer.material.mainTexture = rTex;  shader端:[csharp]HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy#include "UnityCG.cginc"             sampler2D _MainTex;  sampler2D _NoiseTex;        struct v2f {          half4 pos:SV_POSITION;          half2 uv : TEXCOORD0;       float4 srcPos: TEXCOORD1;    };      v2f vert(appdata_full v) {        v2f o;        o.pos = mul (UNITY_MATRIX_MVP, v.vertex);        o.uv = v.texcoord.xy;      o.srcPos = ComputeScreenPos(o.pos);      return o;    }      fixed4 frag(v2f i) : COLOR0 {      float tmp = saturate(1-(length(i.uv-float2(0.5,0.5)))*2)*0.04;                float2 wcoord = (i.srcPos.xy/i.srcPos.w) + tex2D(_NoiseTex, i.uv) * tmp - tmp/2;      return tex2D(_MainTex, wcoord);  }    45)使用RenderTexture制作屏幕特效:[csharp]HYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"viewplain"viewplainHYPERLINK"http://blog.csdn.net/stalendp/article/details/17114135"\o"copy"copy[ExecuteInEditMode]  public class MyScreenEffect : MonoBehaviour {      ...      void OnRenderImage(RenderTexture source, RenderTexture dest) {          Graphics.Blit(source, dest, material);      }  }  如果需要多次渲染,需要使用RenderTexture.GetTemporary生成临时的RenderTexture,这个 方法 快递客服问题件处理详细方法山木方法pdf计算方法pdf华与华方法下载八字理论方法下载 会从unity维护的池中获取,所以在使用完RenderTexture后,尽快调用RenderTexture.ReleaseTemporary使之返回池中。RenderTexture存在于GPU的DRAM中,具体实现可以参
本文档为【unity3d小技巧合集】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: ¥17.0 已有0 人下载
最新资料
资料动态
专题动态
个人认证用户
中式烹调师
暂无简介~
格式:doc
大小:572KB
软件:Word
页数:18
分类:修理服务/居民服务
上传时间:2022-09-13
浏览量:10