Unity3D中的一些技巧总结

以下tip来源于网络(unity wiki、unity fb、unity Twitter等)

1:

When you’re using Debug.Log or related methods, provide the instance of the script so you can click the log output and have the relevant object selected in editor! Debug.Log(“Test”, this);

2:

To remember which color means what on an axis in Unity, just remember the mnemonic: RGB = XYZ.

3:Draw editor gui’s only in active scene view

If you are creating custom editors for unity but only want the gui for that editor to be drawn in the currently active scene view try this …

if (SceneView.mouseOverWindow.GetInstanceID() == SceneView.currentDrawingSceneView.GetInstanceID())
{
    this.DrawGUI(SceneView.currentDrawingSceneView);
}

4:Execute menu items from editor script

If you want to take advantage of functionality that is provided by menu commands you can useEditorApplication.ExecuteMenuItem in your editor scripts to execute them.

5:Screen Resolution

If you need to set the screen resolution of your game via scripting check out Screen.SetResolution.

6:Collider manipulation

Did you know that you can manipulate a game objects collider in the scene view by holding down the ‘Shift’ key. Holding shift will display the colliders control dots. Just drag the dots to adjust the collider!

7:Running Editor Script Code on Launch

If you need to run some script code as soon as the editor has launched you can use the InitializeOnLoad attribute.

8:各平台下的log文件

http://docs.unity3d.com/Manual/LogFiles.html

9:unity的命令行参数

http://docs.unity3d.com/Manual/CommandLineArguments.html

11:Can you hear me now?

Unity provides access to the users microphone via the Microphone class.
http://docs.unity3d.com/ScriptReference/Microphone.html

12:Location awareness

Unity provides support for location awareness such as longitude, latitude, and altitude in the LocationService class.
http://docs.unity3d.com/ScriptReference/LocationService.html

13:Social Platforms

Unity provides built in support for various social platforms including support for custom implementations through the Social class.
http://docs.unity3d.com/ScriptReference/Social.html

14:Gyroscopes

If the device supports it you can use the Gyroscope class to get gyroscopic information about the orientation and acceleration of the device.
http://docs.unity3d.com/ScriptReference/Gyroscope.html

15:EditorApplication

http://docs.unity3d.com/ScriptReference/EditorApplication.html
场景的保存、新建、暂停等等用script模拟Editor相关操作

16:MeshUtility.Optimize

程序生成的mesh可以用这个做优化

http://docs.unity3d.com/ScriptReference/MeshUtility.Optimize.html

17:UI渐变效果

http://pastebin.com/dJabCfWn

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

[AddComponentMenu("UI/Effects/Gradient")]
public class Gradient : BaseVertexEffect {
[SerializeField]
private Color32 topColor = Color.white;
[SerializeField]
private Color32 bottomColor = Color.black;

public override void ModifyVertices(List<UIVertex> vertexList) {
    if (!IsActive()) {
        return;
    }

    int count = vertexList.Count;
    float bottomY = vertexList[0].position.y;
    float topY = vertexList[0].position.y;

    for (int i = 1; i < count; i++) {
        float y = vertexList[i].position.y;
        if (y > topY) {
            topY = y;
        }
        else if (y < bottomY) {
            bottomY = y;
        }
    }

    float uiElementHeight = topY - bottomY;

    for (int i = 0; i < count; i++) {
        UIVertex uiVertex = vertexList[i];
        uiVertex.color = Color32.Lerp(bottomColor, topColor, (uiVertex.position.y - bottomY) / uiElementHeight);
        vertexList[i] = uiVertex;
    }
}
}

18:AABB碰撞检测

http://pastebin.com/BCEgZxSf

using UnityEngine;
using System.Collections;

public static class Aabb

{

public static bool Colliding( GameObject a, GameObject b )
{
    Rect aBox = a.BoxToRect();
    Rect bBox = b.BoxToRect();

    // Find out if these guys intersect
    return Intersect ( aBox, bBox );
}

// This checks the intersection between two rectangles.
public static bool Intersect( Rect a, Rect b ) 
{
    // Basic AABB collision detection. All of these must be true for there to be a collision.
    bool comp1 = a.yMin > b.yMax;
    bool comp2 = a.yMax < b.yMin;
    bool comp3 = a.xMin < b.xMax;
    bool comp4 = a.xMax > b.xMin;

    // This will only return true if all are true.
    return comp1 && comp2 && comp3 && comp4;
}

// This converts a BoxCollider2D to a rectangle for use in determining an intersection
private static Rect BoxToRect ( this GameObject a )
{
    // Finding the BoxCollider2D for the GameObject.
    BoxCollider2D aCollider = a.GetComponent<BoxCollider2D> ();

    // Grabbing the GameObject position, converting it to Vector2.
    Vector2 aPos = a.transform.position.V2();

    // Now that we have the object's worldspace location, we offset that to the BoxCollider's center
    aPos += aCollider.center;
    // From the center, we find the top/left corner by cutting the total height/width in half and 
    // offset by that much
    aPos.x -= aCollider.size.x/2;
    aPos.y += aCollider.size.y/2;

    // Create a rectangle based on the top/left corner, and extending the rectangle 
    // to the width/height
    return new Rect ( aPos.x, aPos.y, aCollider.size.x, -aCollider.size.y );
}

// Converts a Vector 3 to Vector 2
private static Vector2 V2 ( this Vector3 v ) 
{
    // Converts the Vector3 to a Vector2.
    return new Vector2 (v.x, v.y);
}

}

19:Weapon Sway Unity3D

http://pastebin.com/p5XagGuy

//============================================
// ATTACH THIS TO WEAPON
//
// ATTACH WEAPON TO PLAYER GAMEOBJECT
//============================================

using UnityEngine;
using System.Collections;

public class WeaponSwayScript : MonoBehaviour {
public float mouseSensitivity = 10f;
public float maxMoveAmount = 0.5f;
public float smoothSpeed = 3f;

private Vector3 startPos;

private float factorX;
private float factorY;

public bool bRotate;
public float smoothRotationSpeed = 2f;
public float rotateAmount = 45f;

//============================================
// FUNCTIONS
//============================================

void Start()
{
    startPos = transform.localPosition;
}

void Update()
{
    // STORE MOUSE MOVEMENT AMOUNTS, SMOOTH WITH LERP
    factorX = Mathf.Lerp(factorX, -Input.GetAxis("Mouse X") * mouseSensitivity, Time.deltaTime * 10f);
    factorY = Mathf.Lerp(factorY, -Input.GetAxis("Mouse Y") * mouseSensitivity, Time.deltaTime * 10f);

    // CLAMP LIMITS
    if (factorX > maxMoveAmount)
        factorX = maxMoveAmount;

    if (factorX < -maxMoveAmount)
        factorX = -maxMoveAmount;

    if (factorY > maxMoveAmount)
        factorY = maxMoveAmount;

    if (factorY < -maxMoveAmount)
        factorY = -maxMoveAmount;

    // SET TARGET POSITION (START POSITION + MOUSE MOVEMENT)
    Vector3 targetPos = new Vector3(startPos.x + factorX, startPos.y + factorY, startPos.z);

    // APPLY POSITION TO WEAPON, SMOOTH WITH LERP
    transform.localPosition = Vector3.Lerp(transform.localPosition, targetPos, smoothSpeed * Time.deltaTime);

    // ROTATION
    if (bRotate)
    {
        float tiltAroundZ = Input.GetAxis("Mouse X") * rotateAmount;
        float tiltAroundX = Input.GetAxis("Mouse Y") * rotateAmount;
        Vector3 target = new Vector3(tiltAroundX, 0f, tiltAroundZ);
        transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.Euler(target), Time.deltaTime * smoothRotationSpeed);
    }
}
}