[Unity] skill set

Source: Internet
Author: User
Keep the address blog. csdn. netstalendparticipant ledetails17114135 for forwarding. This article will collect unity-related skills and update content continuously. 1) Saving the running state unity cannot be saved during the running state. However, when editing at runtime, you may find better results to save. In this case

Forward, please stay at the address: http://blog.csdn.net/stalendp/article/details/17114135 this article will collect unity related tips and will continually update content. 1) Saving the running state unity cannot be saved during the running state. However, when editing at runtime, you may find better results to save. In this case

Forward, please stay at address: http://blog.csdn.net/stalendp/article/details/17114135

This article will collect unity-related skills and update content continuously.

1) Save the running status

Unity cannot be saved during running. However, when editing at runtime, you may find better results to save. In this case, you can copy the Related Object Tree in "Hierarchy", pause the game, and replace the original one. (In fact, this copy process is a serialization process, which is serialized into the memory; another method is to serialize to the disk, that is, to drag the content to the folder into prefab, the same effect)

2) Layer usage

LayerMask. NameToLayer ("Ground"); // obtain the layer by name

3D Raycast

RaycastHit hit; if (Physics. Raycast (cam3d. ScreenPointToRay (Input. mousePosition), out hit, Mathf. Infinity, (1 <
 
  

2D Raycast

Collider2D h = Physics2D. OverlapPoint (cam2d. ScreenToWorldPoint (Input. mousePosition), (1 <
   
    

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

Save:

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

4) operate componenent

Add:

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

Delete:

Destroy(transform.gameObject.GetComponent
     
      ());
     

5) animation-related


The condition from State Init to state fsShake is: parameter shake = true; written in code:

Triggering fsShake:

void Awake() {    anims = new Animator[(int)FColorType.ColorNum];}....if(needShake) {    curAnim.SetTrigger("shake");}

Disable 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!!!!");    }}....}

Description of the Animator. StringToHash function:

The setBool, setTrigger, and other functions of animator have two parameter forms: one receiving string and the other receiving hash; in fact, Animator uses hash internally to record the corresponding information, therefore, the StringToHash function can be called internally by receiving string functions. If you need to call setTrigger and so on frequently, hash the parameter name to keep itTo improve performance.


Method for obtaining the animation state and animation clip in the state machine animator (refer to the http://answers.unity3d.com/questions/692593/get-animation-clip-length-using-animator.html ):

public static AnimationClip getAnimationClip(Animator anim, string clipName) {UnityEditorInternal.State state = getAnimationState(anim, clipName);return state!=null ? state.GetMotion() as AnimationClip : null;}public static UnityEditorInternal.State getAnimationState(Animator anim, string clipName) {UnityEditorInternal.State state = null;if(anim != null) {UnityEditorInternal.AnimatorController ac = anim.runtimeAnimatorController as UnityEditorInternal.AnimatorController;UnityEditorInternal.StateMachine sm = ac.GetLayer(0).stateMachine;for(int i = 0; i < sm.stateCount; i++) {UnityEditorInternal.State _state = sm.GetState(i);if(state.uniqueName.EndsWith("." + clipName)) {state = _state;}}}return state;}

6) scene switchover

Synchronization method:

Application.LoadLevel(currentName);

Asynchronous mode:

Application.LoadLevelAsync("ARScene");

7) Load Resources

 Resources.Load
     
      (string.Format("{0}{1:D2}", mPrefix, 5));
     

8) Tag VS. Layer

-> Tag is used to query objects.

-> Layer is used to determine which objects can be used by raycast, and is also used in camera render.

9) rotate

Transform. eulerAngles can access rotate's xyz

transform.RotateAround(pivotTransVector, Vector3.up, -0.5f * (tmp-preX) * speed);
10) save data
PlayerPrefs.SetInt("isInit_" + Application.loadedLevelName, 1);

11) animation Encoding

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) traverse sub-objects

Transform[] 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) playback of Sound Effects

Add Auido Source first, set Audio Clip, or add it to the code. Then, call audio. Play () in the Code. refer to the following code:

public AudioClip aClip;...void Start () { ...audio.clip = aClips;audio.Play();...}

In addition, for 3d sound effects, you need to adjust the panLevel in audio Souce to hear the sound. The reason is unclear.

14) debugging skills (Debug)

You can use the OnDrawGizmos function to perform Rectangular areas and perform debugging. For more information, see the function implementation in the UIDraggablePanel. cs file in NGUI.

#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) latency (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) use Random as a seed

Random. seed = System. Environment. TickCount; or Random. seed = System. DateTime. Today. Millisecond;

17) debugging skills (debug), which can be easily printed on the Interface

void OnGUI() {    GUI.contentColor = Color.green;    GUILayout.Label("deltaTime is: " + Time.deltaTime);}

18) send messages separately

SendMessage, BroadcastMessage, etc.

19) pause the game (set timeScale)

Time.timeScale = 0;

20) instantiate a prefab.

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

21) Use Cases of Lerp Functions

// 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 sound at a specific position

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

23) Determination of equal floating point numbers (because floating point numbers have errors, it is best not to use equal signs, especially the calculated results)

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

24) Use a script to modify the value of uniform in the shader.

// Shader Writing Method Properties {... disHeight ("threshold distance", Float) = 3} SubShader {Pass {CGPROGRAM # pragma vertex vert # pragma fragment frag... uniform float disHeight ;... // ==================================================================/modify the value of disHeight In the shader is gameObject. renderer. sharedMaterial. setFloat ("disHeight", height );

25) Get the name Of the current level

Application.loadedLevelName

26) double-click event

void OnGUI() {    Event Mouse = Event.current;    if ( Mouse.isMouse && Mouse.type == EventType.MouseDown && Mouse.clickCount == 2) {        print("Double Click");    }}

27) Date:

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

28) RootAnimation Mobile Script Processing

class 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 effect (BillBoard effect, or sunflower effect, so that the object attaches importance to camera orientation)

public class BillBoard : MonoBehaviour {// Update is called once per framevoid Update () {transform.LookAt(Camera.main.transform.position, -Vector3.up);}}

30) Property Drawers in the script. You can also customize the Property editor.

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

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

Popup seems to be invalid, but the enum type variable can achieve the Popup effect.

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) solutions to lightmapping problems under Mobile

In mobile mode, lightmapping may not respond. You can try to use the shader in mobile to solve the problem. For more information, see: http://forum.unity3d.com/threads/138978-Lightmap-problem-in-iPhone

32) Unity offline draw function (for debug)

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

33) code reuse in Shader (use of CGINCLUDE)


    

34) obtain the length of the AnimationCurve

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

35) in C #, convert string to 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
     
      

36) sorting

list.Sort(delegate(Object a, Object b) { return a.name.CompareTo(b.name); });

37) NGUI-related class relationships:




38) allows the script to be reflected in the editor in Real Time:

Add [ExecuteInEditMode] before the script. For more information, see UISprite.

39) Hide related attributes

Add [HideInInspector] before the attribute, which is also applicable to shader;

For example:

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) serialization of attributes

Serializable attributes can be displayed on the Inspector Panel (hideinininspector can be used to hide them). public attributes can be serialized by default, while private attributes cannot be serialized by default. The private attribute can be serialized and can be modified using [SerializeField. As follows:

[SerializeField] private string ressName = "Sphere";

41) Diversified Shader compilation (Making multiple shader program variants)

Generally, the shader statement is as follows:

# Pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON to compile the Shader into multiple versions. When used, set Material. EnableKeyword and DisableKeyword locally, or set Shader. EnableKeyword and DisableKeyword globally.
42) multiple scene shared content
 void Awake() {    DontDestroyOnLoad(transform.gameObject);}
43) Use Animation to play the AnimationClip created by unity:
First, you need to set the type of the AnimationType to 1 (you need to set it in the Debug mode attribute of the animationClip, as shown in. In addition, if you want to play an animation in animator, the type must be 2 );

      
The Code is as follows:
String clipName = "currentClip"; AnimationClip clip = ...; // set animationClip if (anim = null) {anim = gameObject. addComponent ();} anim. addClip (clip, clipName); anim [clipName]. speed = _ speedScale; // computing time float duration = anim [clipName]. length; duration/= _ speedScale; // play the anim animation. play (clipName); yield return new WaitForSeconds (duration + 0.1f); // animation end action anim. stop (); anim. removeClip (clipName );

44) RenderTexture Full Screen Effect
Cs end:
MeshFilter mesh = quard. GetComponent
        
         
(); // Create the renderTextureRenderTexture rTex = new RenderTexture (int) cam associated with the camera. pixelWidth, (int) cam. pixelHeight, 16.01_cam.tar getTexture = rTex; mesh. renderer. material. mainTexture = rTex;
        
Shader:
#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) Use RenderTexture to create screen effects:
[ExecuteInEditMode]public class MyScreenEffect : MonoBehaviour {...void OnRenderImage(RenderTexture source, RenderTexture dest) {Graphics.Blit(source, dest, material);}}
If you need to perform multiple rendering, you need to use RenderTexture. getTemporary generates a temporary RenderTexture, which is obtained from the pool maintained by unity. Therefore, call RenderTexture as soon as possible after RenderTexture is used. releaseTemporary. RenderTexture exists in the DRAM of GPU. For specific implementation, refer to the Code in Cocos2dx to understand it. (There are specific implementations in CCRenderTexture. cpp ). GPU architecture see: http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter30.html
46) pause unity under certain conditions
When debugging a battle, you need to pause unity under certain conditions to view some object settings. You can use Debug. Break. This must be in debug mode to achieve the effect.
47) pause execution when a specific exception occurs;
By default, unity does not stop running when an exception occurs. However, if nullReferenceException and other exceptions occur, debug them. You can select Run/Exceptions... In the MonoDevelop menu to make relevant settings:

      
48) NGUI performance recommendations
Related Knowledge: 1) In NGUI, a Panel corresponds to a DrawCall (of course, The UISprite in a panel comes from multiple atlas, there will be multiple drawcalls); 2) when the active status of a UISprite or other UIWidget controls changes, DrawCall is re-calculated. 3) the calculation of DrawCall is time consuming. First, the verts, norms, and trans of all uiwidgets under DrawCall are collected, uvs, cols and other information, but also to transmit data to the GPU, relatively time-consuming.
Problem: When a Panel contains a large number of uiwidgets, some of them often change their active status, while others do not. This will cause frequent Calculation of DrawCall.
Performance Improvement Solution: separate controls that frequently change the active state into a single panel. Separate the unchanged parts into another panel.

      
49) set the custom Shader in NGUI and change the properties value.
You can use UITexture to set custom Material. Note that to change the properties value, use the dynamicMaterial of drawCall in UITexture as follows:
UITexture tex=....;tex.drawCall.dynamicMaterial.SetFloat("_percent", du/DU);
50) Identify the InputTouch type in unity:
public enum OperateStatus {OS_Idle=0,OS_Draging=1,OS_Scaling=2}.....void Update () {   ......       TouchPhase tp = Input.GetTouch(0).phase;if(tp==TouchPhase.Ended || tp==TouchPhase.Canceled) {oStatus = OperateStatus.OS_Idle;} else {oStatus = Input.touchCount>1 ? OperateStatus.OS_Scaling : OperateStatus.OS_Draging;}.....}
51) Physical System Performance prompt:
In Unity, physical simulations are involved in static collider and dynamic collider ). Static collision objects refer to objects with the collider attribute but without the rigidbody, and Dynamic Collision objects refer to objects with the collider and rigidbody attributes.
The Unity engine expects static objects to be static and will compute all static objects in the scenario into a thing called static collider cache to accelerate physical simulation. However, if one of the static objects is moved, the system will re-calculate the static collider cache, which costs a lot. Therefore, if an object needs to move frequently, it should be designed as a dynamic object, that is, adding the rigidbody component. As for the effect of the force such as gravity, see "Use Gravity" and "Is Kinematic" attributes in rigidbody.
If the rigidbody is a kinematic, it does not respond to force and can be used to create effects such as flight obstacles. If it is not kinematic, it will respond to foce.
See the following official tutorials for final performance analysis: http://unity3d.com/learn/tutorials/projects/roll-a-ball/collecting-and-counting
52) Comparison of four types of Collider in unity:
       
    
Type Can I move it? Whether to receive Trigger messages Impact of collision? Physical impact?
Static High Cost No No No
Kinematic Rigidbody Yes Yes No No
Character Controller Yes Unknown Yes No
Rigidbody Yes Yes Yes Yes
Observe the table above and find that the more features you have. I did not discuss Character Controller when introducing collision. I added a comparison myself.
In addition, if an object can be affected by a collision, it will certainly be able to receive Collition messages.
For an official detailed table of messages that receive Collision messages and Trigger messages, see the table at the end of the http://docs.unity3d.com/Manual/CollidersOverview.html.
53) attach an object to a surface to keep the up direction of the object consistent with the normal direction of the surface (the object is marked as obj and the surface is marked as suf ):
Method 1:
obj.transform.rotation = Quaternion.FromToRotation(obj.transform.up, suf.transform.up)* obj.transform.rotation;
Method 2:
Vector3 axis = Vector3.Cross(obj.transform.up, suf.transform.up);float angle = Vector3.Angle(obj.transform.up, suf.transform.up);obj.transform.Rotate(axis, angle, Space.World);
54) showFPS code in AngryBots:
@script ExecuteInEditModeprivate var gui : GUIText;private var updateInterval = 1.0;private var lastInterval : double; // Last interval end timeprivate var frames = 0; // Frames over current intervalfunction Start(){    lastInterval = Time.realtimeSinceStartup;    frames = 0;}function OnDisable (){if (gui)DestroyImmediate (gui.gameObject);}function Update(){#if !UNITY_FLASH    ++frames;    var timeNow = Time.realtimeSinceStartup;    if (timeNow > lastInterval + updateInterval)    {if (!gui){var go : GameObject = new GameObject("FPS Display", GUIText);go.hideFlags = HideFlags.HideAndDontSave;go.transform.position = Vector3(0,0,0);gui = go.guiText;gui.pixelOffset = Vector2(5,55);}        var fps : float = frames / (timeNow - lastInterval);var ms : float = 1000.0f / Mathf.Max (fps, 0.00001);gui.text = ms.ToString("f1") + "ms " + fps.ToString("f2") + "FPS";        frames = 0;        lastInterval = timeNow;    }#endif}
55) Hierarchy name-based alphabetic sorting:
public class AlphaNumericSort : BaseHierarchySort{public override int Compare(GameObject lhs, GameObject rhs){if (lhs == rhs) return 0;if (lhs == null) return -1;if (rhs == null) return 1;return EditorUtility.NaturalCompare(lhs.name, rhs.name);}}

After the above Code is put into the project, the sorting button will appear in Hierarchy, as shown below:

      
Official address for BaseHierarchySort: http://docs.unity3d.com/ScriptReference/BaseHierarchySort.html

      

      

      

     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.