首页 > 代码库 > Unity技巧集合
Unity技巧集合
地址:http://blog.csdn.net/stalendp/article/details/17114135
这篇文章将收集unity的相关技巧,会不断地更新内容。
1)保存运行中的状态
unity在运行状态时是不能够保存的。但在运行时编辑的时候,有时会发现比较好的效果想保存。这时可以在 “Hierarchy”中复制相关对象树,暂停游戏后替换原来的,就可以了。
2)Layer的用法
LayerMask.NameToLayer("Ground"); // 通过名字获取layer
3D Raycast
- RaycastHit hit;
- if(Physics.Raycast(cam3d.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, (1<<LayerMask.NameToLayer("Ground")))) {
- ...
- }
2D Raycast
- Collider2D h = Physics2D.OverlapPoint(cam2d.ScreenToWorldPoint(Input.mousePosition), (1<<LayerMask.NameToLayer("xxx")));
- if(h) {
- ...
- }
3)物理摄像头取色(WebCamTexture)
- 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;
- }
保存截图:
- System.IO.File.WriteAllBytes(Application.dataPath + "/test.png", exactCamData().EncodeToPNG());
4) 操作componenent
添加:
- CircleCollider2D cld = (CircleCollider2D)colorYuan[i].AddComponent(typeof(CircleCollider2D));
- cld.radius = 1;
删除:
- Destroy(transform.gameObject.GetComponent<SpriteRenderer>());
5)动画相关
状态Init到状态fsShake的的条件为:参数shake==true;代码中的写法:
触发fsShake:
- void Awake() {
- anims = new Animator[(int)FColorType.ColorNum];
- }
- ....
- if(needShake) {
- curAnim.SetTrigger("shake");
- }
关闭fsShake
- 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的切换
同步方式:
- Application.LoadLevel(currentName);
异步方式:
- Application.LoadLevelAsync("ARScene");
7)加载资源
- Resources.Load<Texture>(string.Format("{0}{1:D2}", mPrefix, 5));
8)Tag VS. Layer
-> Tag用来查询对象
-> Layer用来确定哪些物体可以被raycast,还有用在camera render中
9)旋转
transform.eulerAngles 可以访问 rotate的 xyz
- transform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);
10)保存数据
- 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) 遍历子对象
- 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(), 参考如下代码:
- public AudioClip aClip;
- ...
- void Start () {
- ...
- audio.clip = aClips;
- audio.Play();
- ...
- }
另外,如果是3d音效的话,需要调整audio Souce中的panLevel才能听到声音,不清楚原因。
14)调试技巧(Debug)
可以在OnDrawGizmos函数来进行矩形区域等,达到调试的目的,请参考NGUI中的UIDraggablePanel.cs文件中的那个函数实现。
- #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)
- 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做种子
- Random.seed = System.Environment.TickCount;
- 或者
- Random.seed = System.DateTime.Today.Millisecond;
17) 调试技巧(debug),可以把值方便地在界面上打印出来
- void OnGUI() {
- GUILayout.Label("deltaTime is: " + Time.deltaTime);
- }
18)分发消息
sendMessage, BroadcastMessage等
19) 游戏暂停(对timeScale进行设置)
- Time.timeScale = 0;
20) 实例化一个prefab
- Rigidbody2D propInstance = Instantiate(backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;
21)Lerp函数的使用场景
- // 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)在特定位置播放声音
- // Play the bomb laying sound.
- AudioSource.PlayClipAtPoint(bombsAway,transform.position);
23) 浮点数相等的判断(由于浮点数有误差, 所以判断的时候最好不要用等号,尤其是计算出来的结果)
- if (Mathf.Approximately(1.0, 10.0/10.0))
- print ("same");
24)通过脚本修改shader中uniform的值
- //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的名称
- Application.loadedLevelName
26)双击事件
- void OnGUI() {
- Event Mouse = Event.current;
- if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) {
- print("Double Click");
- }
- }
27) 日期:
- System.DateTime dd = System.DateTime.Now;
- GUILayout.Label(dd.ToString("M/d/yyyy"));
28) RootAnimation中移动的脚本处理
- class RootControl : MonoBehaviour {
- void OnAnimatorMove() {
- Animator anim = GetComponent<Animator>();
- if(anim) {
- Vector3 newPos = transform.position;
- newPos.z += anim.GetFloat("Runspeed") * Time.deltaTime;
- transform.position = newPos;
- }
- }
- }
29) BillBoard效果(广告牌效果,或者向日葵效果,使得对象重视面向摄像机)
- public class BillBoard : MonoBehaviour {
- // Update is called once per frame
- void Update () {
- transform.LookAt(Camera.main.transform.position, -Vector3.up);
- }
- }
30)script中的属性编辑器(Property Drawers),还可以自定义属性编辑器
参考: http://blogs.unity3d.com/2012/09/07/property-drawers-in-unity-4/
其中Popup好像无效,但是enum类型的变量,能够达到Popup的效果
- public 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问题的解决方案
在mobile模式下,lightmapping可能没有反应,可以尝试使用mobile下的shader,可以解决问题。更多请参考:http://forum.unity3d.com/threads/138978-Lightmap-problem-in-iPhone
32) Unity下画线的功能(用于debug)
- Debug.DrawLine (Vector3.zero, new Vector3 (10, 0, 0), Color.red);
33)Shader中代码的复用(CGINCLUDE的使用)
- Shader "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的时长
- _curve.keys[_curve.length-1].time;
35)C#中string转变成byte[]:
- byte[] 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 <bpara.length;i ++){char[i]=system.convert.tochar(bpara[i]);}
36) 排序
- list.Sort(delegate(Object a, Object b) { return a.name.CompareTo(b.name); });
37) NGUI的相关类关系:
38)使得脚本能够在editor中实时反映:
在脚本前加上:[ExecuteInEditMode], 参考UISprite。
39)隐藏相关属性
属性前加上 [HideInInspector],在shader中也适用;
比如:
- public class ResourceLoad : MonoBehaviour {
- [HideInInspector] public string ressName = "Sphere";
- public string baseUrl = "http://192.168.56.101/ResUpdate/{0}.assetbundle";
- Shader "stalendp/imageShine" {
- Properties {
- [HideInInspector] _image ("image", 2D) = "white" {}
- _percent ("_percent", Range(-5, 5)) = 1
- _angle("_angle", Range(0, 1)) = 0
- }
40)属性的序列化
可被序列化的属性,可以显示在Inspector面板上(可以使用HideInInspector来隐藏);public属性默认是可被序列化的,private默认是不可序列化的。使得private属性可被序列化,可以使用[SerializeField]来修饰。如下:
- [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共享内容
- void Awake() {
- DontDestroyOnLoad(transform.gameObject);
- }