地址:http://blog.csdn.net/stalendp/article/details/17114135

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

1)保存运行中的状态

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

2)Layer的用法

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

3D Raycast

[csharp] view plaincopy

  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 plaincopy

  1. Collider2D h = Physics2D.OverlapPoint(cam2d.ScreenToWorldPoint(Input.mousePosition), (1<<LayerMask.NameToLayer("xxx")));
  2. if(h) {
  3. ...
  4. }

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

[csharp] view plaincopy

  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 plaincopy

  1. System.IO.File.WriteAllBytes(Application.dataPath + "/test.png", exactCamData().EncodeToPNG());

4) 操作componenent

添加:

[csharp] view plaincopy

  1. CircleCollider2D cld = (CircleCollider2D)colorYuan[i].AddComponent(typeof(CircleCollider2D));
  2. cld.radius = 1;

删除:

[csharp] view plaincopy

  1. Destroy(transform.gameObject.GetComponent<SpriteRenderer>());

5)动画相关

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

触发fsShake:

[csharp] view plaincopy

  1. void Awake() {
  2. anims = new Animator[(int)FColorType.ColorNum];
  3. }
  4. ....
  5. if(needShake) {
  6. curAnim.SetTrigger("shake");
  7. }

关闭fsShake

[csharp] view plaincopy

  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. }

6)scene的切换

同步方式:

[csharp] view plaincopy

  1. Application.LoadLevel(currentName);

异步方式:

[csharp] view plaincopy

  1. Application.LoadLevelAsync("ARScene");

7)加载资源

[csharp] view plaincopy

  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 plaincopy

  1. transform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);

10)保存数据

[csharp] view plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  1. Random.seed = System.Environment.TickCount;
  2. 或者
  3. Random.seed = System.DateTime.Today.Millisecond;

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

[csharp] view plaincopy

  1. void OnGUI() {
  2. GUILayout.Label("deltaTime is: " + Time.deltaTime);
  3. }

18)分发消息

sendMessage, BroadcastMessage等

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

[csharp] view plaincopy

  1. Time.timeScale = 0;

20) 实例化一个prefab

[csharp] view plaincopy

  1. Rigidbody2D propInstance = Instantiate(backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;

21)Lerp函数的使用场景

[csharp] view plaincopy

  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 plaincopy

  1. // Play the bomb laying sound.
  2. AudioSource.PlayClipAtPoint(bombsAway,transform.position);

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

[csharp] view plaincopy

  1. if (Mathf.Approximately(1.0, 10.0/10.0))
  2. print ("same");

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

[csharp] view plaincopy

  1. //shader的写法
  2. Properties {
  3. ...
  4. disHeight ("threshold distance", Float) = 3
  5. }
  6. SubShader {
  7. Pass {
  8. CGPROGRAM
  9. #pragma vertex vert
  10. #pragma fragment frag
  11. ...
  12. uniform float disHeight;
  13. ...
  14. // ===================================
  15. // 修改shader中的disHeight的值
  16. gameObject.renderer.sharedMaterial.SetFloat("disHeight", height);

25) 获取当前level的名称

[csharp] view plaincopy

  1. Application.loadedLevelName

26)双击事件

[csharp] view plaincopy

  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 plaincopy

  1. System.DateTime dd = System.DateTime.Now;
  2. GUILayout.Label(dd.ToString("M/d/yyyy"));

28)  RootAnimation中移动的脚本处理

[csharp] view plaincopy

  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 plaincopy

 
  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/

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

[csharp] view plaincopy

 
  1. public class Example : MonoBehaviour {
  2. public string playerName = "Unnamed";
  3. [Multiline]
  4. public string playerBiography = "Please enter your biography";
  5. [Popup ("Warrior", "Mage", "Archer", "Ninja")]
  6. public string @class = "Warrior";
  7. [Popup ("Human/Local", "Human/Network", "AI/Easy", "AI/Normal", "AI/Hard")]
  8. public string controller;
  9. [Range (0, 100)]
  10. public float health = 100;
  11. [Regex (@"^(?:\d{1,3}\.){3}\d{1,3}$", "Invalid IP address!\nExample: '127.0.0.1'")]
  12. public string serverAddress = "192.168.0.1";
  13. [Compact]
  14. public Vector3 forward = Vector3.forward;
  15. [Compact]
  16. public Vector3 target = new Vector3 (100, 200, 300);
  17. public ScaledCurve range;
  18. public ScaledCurve falloff;
  19. [Angle]
  20. public float turnRate = (Mathf.PI / 3) * 2;
  21. }

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

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

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

[csharp] view plaincopy

 
  1. Debug.DrawLine (Vector3.zero, new Vector3 (10, 0, 0), Color.red);

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

[cpp] view plaincopy

 
  1. Shader "Self-Illumin/AngryBots/InterlacePatternAdditive" {
  2. Properties {
  3. _MainTex ("Base", 2D) = "white" {}
  4. //...
  5. }
  6. CGINCLUDE
  7. #include "UnityCG.cginc"
  8. sampler2D _MainTex;
  9. //...
  10. struct v2f {
  11. half4 pos : SV_POSITION;
  12. half2 uv : TEXCOORD0;
  13. half2 uv2 : TEXCOORD1;
  14. };
  15. v2f vert(appdata_full v) {
  16. v2f o;
  17. // ...
  18. return o;
  19. }
  20. fixed4 frag( v2f i ) : COLOR {
  21. // ...
  22. return colorTex;
  23. }
  24. ENDCG
  25. SubShader {
  26. Tags {"RenderType" = "Transparent" "Queue" = "Transparent" "Reflection" = "RenderReflectionTransparentAdd" }
  27. Cull Off
  28. ZWrite Off
  29. Blend One One
  30. Pass {
  31. CGPROGRAM
  32. #pragma vertex vert
  33. #pragma fragment frag
  34. #pragma fragmentoption ARB_precision_hint_fastest
  35. ENDCG
  36. }
  37. }
  38. FallBack Off
  39. }

34)获取AnimationCurve的时长

[csharp] view plaincopy

 
  1. _curve.keys[_curve.length-1].time;

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

[csharp] view plaincopy

 
  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 plaincopy

 
  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 plaincopy

 
  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 plaincopy

 
  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 plaincopy

 
  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 plaincopy

 
  1. void Awake() {
  2. DontDestroyOnLoad(transform.gameObject);
  3. }

Unity技巧集合的更多相关文章

  1. 教你50招提升ASP.NET性能(十三):精选技巧集合

    (19)A selection of tips 招数19: 精选技巧集合 Including height and width in <img /> tags will allow you ...

  2. git使用技巧集合(持续更新中)

    git使用技巧集合(持续更新中) 在团队协作中,git.svn等工具是非常重要的,在此只记录一些git使用过程中遇到的问题以及解决方法,并且会持续更新. 1.git commit之后,还没push,如 ...

  3. PyCharm常用技巧集合

    PyCharm常用技巧集合 一.添加或者修改文件模板 File>settings>Editor>File and Code Templates>Python Script 你可 ...

  4. 有趣而又被忽略的Unity技巧

    0x00 前言 本文的内容主要来自YouTube播主Brackeys的视频TOP 10 UNITY TIPS 和TOP 10 UNITY TIPS #2.在此基础上经过自己的实践和筛选之后,选择了几个 ...

  5. Windows Azure一些小技巧集合

    我最近做了一个Windows Azure上面的项目,自己在做的过程中遇到了很多问题.有的是我自己摸索解决,有的是到网上寻找零碎的信息结合起来解决的.我感觉应当把某些解决方法集中一下,方便我以后查阅,也 ...

  6. 【Unity技巧】使用单例模式Singleton

    这几天想把在实习里碰到的一些好的技巧写在这里,也算是对实习的一个总结.好啦,今天要讲的是在Unity里应用一种非常有名的设计模式——单例模式. 开场白 单例模式的简单介绍请看前面的链接,当然网上还有很 ...

  7. 【Unity技巧】自定义消息框(弹出框)

    写在前面 这一篇我个人认为还是很常用的,一开始也是实习的时候学到的,所以我觉得实习真的是一个快速学习工程技巧的途径. 提醒:这篇教程比较复杂,如果你不熟悉NGUI.iTween.C#的回调函数机制,那 ...

  8. 【Unity技巧】开发技巧(技巧篇)

    写在前面 和备忘录篇一样,这篇文章旨在总结Unity开发中的一些设计技巧,当然这里只是我通过所见所闻总结的东西,如果有不对之处欢迎指出. 技巧1:把全局常量放到一个单独的脚本中 很多时候我们需要一些常 ...

  9. unity技巧

    在之前的程序编写过程中,虽然对相关的方法进行了实例化,但是在运行的时候总是会出现“未将对象引用设置到对象的实例”,出现该种问题的原因是由于在实例化后,没有对实例化进行引用赋值,所以导致相关变量无法在其 ...

随机推荐

  1. 浅谈js数组中的length属性

    前言 一位正在学习前端的菜鸟,虽菜,但还未放弃. 内容 首先,我们都知道每个数组都有一个length属性 这个length属性一般我们用来循环遍历的约束,一般我们都会把他认为是该数组里面有几个元素这个 ...

  2. 【AHOI2009】中国象棋 题解(线性DP+数学)

    前言:这题主要是要会设状态,状态找对了问题迎刃而解. --------------------------- 题目描述 这次小可可想解决的难题和中国象棋有关,在一个N行M列的棋盘上,让你放若干个炮(可 ...

  3. Elasticsearch从入门到放弃:瞎说Mapping

    前面我们聊了 Elasticsearch 的索引.搜索和分词器,今天再来聊另一个基础内容-- Mapping. Mapping 在 Elasticsearch 中的地位相当于关系型数据库中的 sche ...

  4. 2020重新出发,JAVA语言,什么是JAVA?

    @ 目录 什么是 java? JAVA三大体系 Java SE Java EE JavaME java的主要特性和优势 1. 面向对象 2. 平台无关性 3. 可移植性 4. 简单性 5. 解释执行 ...

  5. CSS3 新添选择器

    目录 属性选择器 结构伪类选择器 伪元素选择器 属性选择器 属性选择器可以元素特定属性来进行选择,这样就可以不借助于类选择器或id选择器 选择符 简述 E[att] 选择具有att属性的E元素 E[a ...

  6. C#LeetCode刷题之#344-反转字符串​​​​​​​(Reverse String)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3933 访问. 编写一个函数,其作用是将输入的字符串反转过来. 输 ...

  7. C#LeetCode刷题之#122-买卖股票的最佳时机 II(Best Time to Buy and Sell Stock II)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4032 访问. 给定一个数组,它的第 i 个元素是一支给定股票第  ...

  8. LNK2005 连接错误解决办法 2009-10-30 12:13

    nafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@ ...

  9. 简单快速导出word文档

    最近,我写公司项目word导出功能,应该只有2小时的工作量,却被硬生生的拉长2天,项目上线到业务正常运行也被拉长到2个星期. 为什么如此浪费时间呢? 1)公司的项目比较老,采用硬编码模式,意味着wor ...

  10. 【NOIP必备攻略】 基本noilinux使用方法

    现在linux系统已经成为了NOIP竞赛的一大操作系统,如果连最基础的操作都不会,那就更别提怎么得分了,万一操作失误,可就爆零了.所以小编特意发这样一篇博客,教你快速上手noilinux! ▎ 常用操 ...