1. 程式人生 > >Unity3D入門 UnityAPI常用方法和類

Unity3D入門 UnityAPI常用方法和類

時間函式:

這裡只列舉了一部分,更多的看Scripting API

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

public class API02Time : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Debug.Log("Time.deltaTime:" + Time.deltaTime);//完成最後一幀(只讀)所需的時間(秒)
        Debug.Log("Time.fixedDeltaTime:" + Time.fixedDeltaTime);//執行物理和其他固定幀速率更新(如MonoBehaviour的FixedUpdate)的間隔,以秒為單位。
        Debug.Log("Time.fixedTime:" + Time.fixedTime);//最新的FixedUpdate啟動時間(只讀)。這是自遊戲開始以來的時間單位為秒。
        Debug.Log("Time.frameCount:" + Time.frameCount);//已通過的幀總數(只讀)。
        Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);//遊戲開始後以秒為單位的實時時間(只讀)。
        Debug.Log("Time.smoothDeltaTime:" + Time.smoothDeltaTime);//平滑的時間(只讀)。
        Debug.Log("Time.time:" + Time.time);//此幀開頭的時間(僅讀)。這是自遊戲開始以來的時間單位為秒。
        Debug.Log("Time.timeScale:" + Time.timeScale);//時間流逝的尺度。這可以用於慢動作效果。
        Debug.Log("Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);//此幀已開始的時間(僅讀)。這是自載入上一個級別以來的秒時間。
        Debug.Log("Time.unscaledTime:" + Time.unscaledTime);//此幀的時間尺度無關時間(只讀)。這是自遊戲開始以來的時間單位為秒。

        float time0 = Time.realtimeSinceStartup;
        for(int i = 0; i < 1000; i++)
        {
            Method();
        }
        float time1 = Time.realtimeSinceStartup;
        Debug.Log("總共耗時:" + (time1 - time0));
	}

    void Method()
    {
        int i = 2;
        i *= 2;
        i *= 2;
    }
}

GameObject:

建立物體的3種方法:
    1 構造方法    
    2 Instantiate   可以根據prefab 或者 另外一個遊戲物體克隆
    3 CreatePrimitive  建立原始的幾何體

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

public class API03GameObject : MonoBehaviour {

	void Start () {
        // 1 第一種,構造方法
        GameObject go = new GameObject("Cube");
        // 2 第二種
        //根據prefab 
        //根據另外一個遊戲物體
        GameObject.Instantiate(go);
        // 3 第三種 建立原始的幾何體
        GameObject.CreatePrimitive(PrimitiveType.Plane);
        GameObject go2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
	}
}

AddComponent:新增元件,可以新增系統元件或者自定義的指令碼

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

public class API03GameObject : MonoBehaviour {

	void Start () {
        GameObject go = new GameObject("Cube");
        go.AddComponent<Rigidbody>();//新增系統元件
        go.AddComponent<API01EventFunction>();//新增自定義指令碼
	}
}

禁用和啟用遊戲物體:
    activeSelf:自身的啟用狀態
    activeInHierarchy:在Hierarchy的啟用狀態
    SetActive(bool):設定啟用狀態

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

public class API03GameObject : MonoBehaviour {

	void Start () {
        GameObject go = new GameObject("Cube");
        Debug.Log(go.activeInHierarchy);
        go.SetActive(false);
        Debug.Log(go.activeInHierarchy);
	}
}

遊戲物體查詢:

Find:按名稱查詢GameObject並返回它
FindObjectOfType:根據型別返回型別的第一個活動載入物件
FindObjectsOfType:根據型別返回型別的所有活動載入物件的列表
FindWithTag:根據標籤返回一個活動的GameObject標記。如果沒有找到GameObject,則返回NULL。
FindGameObjectsWithTag:根據標籤返回活動遊戲物件標記的列表。如果沒有找到GameObject,則返回空陣列。
transform.Find

GameObject.Find和transform.Find的區別: 
public static GameObject Find(string name); 
適用於整個遊戲場景中名字為name的所有處於活躍狀態的遊戲物件。如果在場景中有多個同名的活躍的遊戲物件,在多次執行的時候,結果是固定的。

public Transform Find(string name); 
適用於查詢遊戲物件子物件名字為name的遊戲物件,不管該遊戲物件是否是啟用狀態,都可以找到。只能是遊戲物件直接的子游戲物件。

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

public class API03GameObject : MonoBehaviour {

	void Start () {
        Light light = FindObjectOfType<Light>();
        light.enabled = false;
        Transform[] ts = FindObjectsOfType<Transform>();
        foreach (Transform t in ts)
        {
            Debug.Log(t);
        }

        GameObject mainCamera = GameObject.Find("Main Camera");
        GameObject[] gos = GameObject.FindGameObjectsWithTag("MainCamera");
        GameObject gos1 = GameObject.FindGameObjectWithTag("Finish");
	}
}

遊戲物體間訊息的傳送:

    BroacastMessage:傳送訊息,向下傳遞(子)
    SendMessage:傳送訊息,需要目標target
    SendMessageUpwards:傳送訊息,向上傳遞(父)

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

public class API04Message : MonoBehaviour {
    private GameObject son;
	
	void Start () {
        son = GameObject.Find("Son");

        // 向下傳遞訊息  
        // SendMessageOptions.DontRequireReceiver表示可以沒有接收者
        //BroadcastMessage("Test", null, SendMessageOptions.DontRequireReceiver);
        // 廣播訊息
        son.SendMessage("Test", null, SendMessageOptions.DontRequireReceiver);
        // 向上傳遞訊息	
        //SendMessageUpwards("Test", null, SendMessageOptions.DontRequireReceiver);
	}
	
}

查詢遊戲元件:

GetComponet(s):查詢單個(所有)遊戲元件
GetComponet(s)InChildren:查詢children中單個(所有)遊戲元件
GetComponet(s)InParent:查詢parent中單個(所有)遊戲元件

注意:如果是查詢單個,若找到第一個後,直接返回,不再向後查詢

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

public class API05GetComponent : MonoBehaviour {

	void Start () {
        Light light = this.transform.GetComponent<Light>();
        light.color = Color.red;
	}
	
}

函式呼叫Invoke:

    Invoke:呼叫函式
    InvokeRepeating:重複呼叫
    CancelInvoke:取消呼叫
    IsInvoking:函式是否被呼叫

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

public class API06Invoke : MonoBehaviour {

	void Start () {
        // Invoke(函式名,延遲時間)
        //Invoke("Attack", 3);	

        // InvokeRepeating(函式名,延遲時間,呼叫間隔)
        InvokeRepeating("Attack", 4, 2);

        // CancelInvoke(函式名)
        //CancelInvoke("Attack");
	}

    void Update()
    {
        // 判斷是否正在迴圈執行該函式
        bool res = IsInvoking("Attack");
        print(res);
    }

    void Attack()
    {
        Debug.Log("開始攻擊");
    }
}

協同程式:

    定義使用IEnumerator
    返回使用yield
    呼叫使用StartCoroutine
    關閉使用StopCoroutine
                StopAllCoroutine
    延遲幾秒:yield return new WaitForSeconds(time);

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

public class API08Coroutine : MonoBehaviour
{
    public GameObject cube;
    private IEnumerator ie;

    void Start()
    {
        print("協程開啟前");
        StartCoroutine(ChangeColor());
        //協程方法開啟後,會繼續執行下面的程式碼,不會等協程方法執行結束才繼續執行
        print("協程開啟後");
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ie = Fade();
            StartCoroutine(ie);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            StopCoroutine(ie);
        }
    }

    IEnumerator Fade()
    {
        for (; ; )
        {
            Color color = cube.GetComponent<MeshRenderer>().material.color;
            Color newColor = Color.Lerp(color, Color.red, 0.02f);
            cube.GetComponent<MeshRenderer>().material.color = newColor;
            yield return new WaitForSeconds(0.02f);
            if (Mathf.Abs(Color.red.g - newColor.g) <= 0.01f)
            {
                break;
            }
        }
    }

    IEnumerator ChangeColor()
    {
        print("hahaColor");
        yield return new WaitForSeconds(3);
        cube.GetComponent<MeshRenderer>().material.color = Color.blue;
        print("hahaColor");
        yield return null;
    }
}

滑鼠相關事件函式:

    OnMouseDown:滑鼠按下
    OnMouseUp:滑鼠擡起
    OnMouseDrag:滑鼠拖動
    OnMouseEnter:滑鼠移上
    OnMouseExit:滑鼠移開
    OnMouseOver:滑鼠在物體上
    OnMouseUpAsButton:滑鼠移開時觸發,且移上和移開在同一物體上才會觸發

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

public class API08OnMouseEventFunction : MonoBehaviour {

    void OnMouseDown()
    {
        print("Down"+gameObject);
    }
    void OnMouseUp()
    {
        print("up" + gameObject);
    }
    void OnMouseDrag()
    {
        print("Drag" + gameObject);
    }
    void OnMouseEnter()
    {
        print("Enter");
    }
    void OnMouseExit()
    {
        print("Exit");
    }
    void OnMouseOver()
    {
        print("Over");
    }
    void OnMouseUpAsButton()
    {
        print("Button" + gameObject);
    }
	
}

Mathf類:

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

public class API09Mathf : MonoBehaviour {

    public Transform cube;
    public int a = 8;
    public int b = 20;
    public float t = 0;
    public float speed = 3;
    void Start()
    {
        /* 靜態變數 */
        // 度數--->弧度
        print(Mathf.Deg2Rad);
        // 弧度--->度數
        print(Mathf.Rad2Deg);
        // 無窮大
        print(Mathf.Infinity);
        // 無窮小
        print(Mathf.NegativeInfinity);
        // 無窮小,接近0    
        print(Mathf.Epsilon);
        // π
        print(Mathf.PI);


        /* 靜態方法 */
        // 向下取整
        Debug.Log(Mathf.Floor(10.2F));
        Debug.Log(Mathf.Floor(-10.2F));

        // 取得離value最近的2的某某次方數
        print(Mathf.ClosestPowerOfTwo(2));//2
        print(Mathf.ClosestPowerOfTwo(3));//4
        print(Mathf.ClosestPowerOfTwo(4));//4
        print(Mathf.ClosestPowerOfTwo(5));//4
        print(Mathf.ClosestPowerOfTwo(6));//8
        print(Mathf.ClosestPowerOfTwo(30));//32

        // 最大最小值
        print(Mathf.Max(1, 2, 5, 3, 10));//10
        print(Mathf.Min(1, 2, 5, 3, 10));//1

        // a的b次方
        print(Mathf.Pow(4, 3));//64 
        // 開平方根
        print(Mathf.Sqrt(3));//1.6

        cube.position = new Vector3(0, 0, 0);
    }

    void Update()
    {
        // Clamp(value,min,max):把一個值限定在一個範圍之內
        cube.position = new Vector3(Mathf.Clamp(Time.time, 1.0F, 3.0F), 0, 0);
        Debug.Log(Mathf.Clamp(Time.time, 1.0F, 3.0F));

        // Lerp(a,b,t):插值運算,從a到b的距離s,每次運算到這個距離的t*s
        // Lerp(0,10,0.1)表示從0到10,每次運動剩餘量的0.1,第一次運動到1,第二次運動到0.9...
        //print(Mathf.Lerp(a, b, t));

        float x = cube.position.x;
        //float newX = Mathf.Lerp(x, 10, Time.deltaTime);
        // MoveTowards(a,b,value):移動,從a到b,每次移動value
        float newX = Mathf.MoveTowards(x, 10, Time.deltaTime*speed);
        cube.position = new Vector3(newX, 0, 0);

        // PingPong(speed,distance):像乒乓一樣來回運動,速度為speed,範圍為0到distance
        print(Mathf.PingPong(t, 20));
        cube.position = new Vector3(5+Mathf.PingPong(Time.time*speed, 5), 0, 0);
    }
    
}

Input類:

    靜態方法:
        GetKeyDown(KeyCode):按鍵按下
        GetKey(KeyCode):按鍵按下沒鬆開
        GetKeyUp(KeyCode):按鍵鬆開
            KeyCode:鍵盤按鍵碼,可以是鍵碼(KeyCode.UP),也可以是名字("up")
        GetMouseButtonDown(0 or 1 or 2):滑鼠按下
        GetMouseButton(0 or 1 or 2):滑鼠按下沒鬆開
        GetMouseButtonUp(0 or 1 or 2):滑鼠鬆開
            0:左鍵    1:右鍵      2:中鍵
        GetButtonDown(Axis):虛擬按鍵按下
        GetButton(Axis):虛擬按鍵按下沒鬆開
        GetButtonUp(Axis):虛擬按鍵鬆開
            Axis:虛擬軸名字
        GetAxis(Axis):返回值為float,上面的是返回bool
            cube.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal")*10);
    靜態變數:
        anyKeyDown:任何鍵按下(滑鼠+鍵盤)
        mousePosition:滑鼠位置

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

public class API10Input : MonoBehaviour {

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            print("KeyDOwn");
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            print("KeyUp");
        }
        if (Input.GetKey(KeyCode.Space))
        {
            print("Key");
        }


        if (Input.GetMouseButton(0))
            Debug.Log("Pressed left click.");


        if (Input.GetMouseButtonDown(0))
            Debug.Log("Pressed left click.");


        if (Input.GetButtonDown("Horizontal"))
        {
            print("Horizontal Down");
        }

        // GetAxis:這樣使用有加速減速效果,如果是速度改變等情況不會突變
        //this.transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal") * 10);

        //GetAxisRaw:沒有加速減速效果,速度改變等情況直接突變
        this.transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxisRaw("Horizontal") * 10);


        if (Input.anyKeyDown)
        {
            print("any key down");
        }

        print(Input.mousePosition);

    }
}

Input輸入類之觸控事件:  推薦使用Easytouch外掛

    Input.touches.Length:觸控點個數

    Input.touches[i]:獲取第i個觸控點資訊

    touch1.position:觸控點位置

    touch1.phase:觸控點狀態

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

public class TouchTest : MonoBehaviour {

	// Update is called once per frame
	void Update () {
        //Debug.Log(Input.touches.Length);
        if (Input.touches.Length > 0)
        {
            Touch touch1 = Input.touches[0];
            //touch1.position;
            TouchPhase phase  = touch1.phase;
        }
	}
}

Vector2

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

public class API11Vector2 : MonoBehaviour {

    void Start()
    {
        /* 靜態變數 */

        // up,down,left,right,one,zero:分別表示點(0,1)(0,-1)(-1,0)(1,0)(1,1)(0,0)
        print(Vector2.down);
        print(Vector2.up);
        print(Vector2.left);
        print(Vector2.right);
        print(Vector2.one);
        print(Vector2.zero);

        // x,y:x座標,y座標(如果有一個向量Vector2 vec,也可以使用vec[0]和vec[1]來表示x和y座標)
        Vector2 vec1 = new Vector2(3, 4);
        Debug.Log("x:" + vec1.x);
        Debug.Log("x:" + vec1[0]);
        Debug.Log("y:" + vec1.y);
        Debug.Log("x:" + vec1[1]);

        // magnitude:向量的長度
        Debug.Log(vec1.magnitude);

		// sqrMagnitude:向量的長度的平方(即上面的沒開根號前,如果只是用來比較的話,不需要開根號)
        Debug.Log(vec1.sqrMagnitude);

        // normalized:返回該向量的單位化向量(如果有一向量,返回一個新向量,方向不變,但長度變為1)
        Debug.Log(vec1.normalized);

		// normalize:返回自身,自身被單位化
        vec1.Normalize();
        Debug.Log("x:" + vec1.x);
        Debug.Log("y:" + vec1.y);

        // 向量是結構體,值型別,需要整體賦值
        transform.position = new Vector3(3, 3, 3);
        Vector3 pos = transform.position;
        pos.x = 10;
        transform.position = pos;


        /* 靜態方法 */

        // Angle(a,b):返回兩個向量的夾角
        Vector2 a = new Vector2(2, 2);
        Vector2 b = new Vector2(3, 4);
        Debug.Log(Vector2.Angle(a, b));

        // ClampMagnitude(a,length):限定長度,如果a>length,將向量a按比例縮小到長度為length
        Debug.Log(Vector2.ClampMagnitude(b, 2));

        // Distance(a,b):返回兩個向量(點)之間的距離
        Debug.Log(Vector2.Distance(a, b));

        // Lerp(a,b,x):在向量a,b之間取插值。最終值為(a.x + a.x * (b.x - a.x), a.y + a.y * (b.y - a.y))
        Debug.Log(Vector2.Lerp(a, b, 0.5f));
        Debug.Log(Vector2.LerpUnclamped(a, b, 0.5f));

        // Max,Min:返回兩向量最大最小
        Debug.Log(Vector2.Max(a, b));

        // + - * /:向量之間可以加減,不能乘除,可以乘除普通數字
        Vector2 res = b - a;//1,2
        print(res);
        print(res * 10);
        print(res / 5);
        print(a + b);
        print(a == b);

    }


    public Vector2 a = new Vector2(2, 2);
    public Vector2 target = new Vector2(10, 3);
    void Update()
    {
        // MoveTowards(a,b,speed):從a到b,速度為speed
        a = Vector2.MoveTowards(a, target, Time.deltaTime);
    }

}

Random:隨機數

    靜態方法:
        Range(a,b):生成>=a且<b的隨機數    若a和b都為整數,則生成整數
        InitState(seed):使用隨機數種子初始化狀態
            Random.InitState((int)System.DateTime.Now.Ticks);
    靜態變數:
        value:生成0到1之間的小數,包括0和1   
        state:獲取當前狀態(即隨機數種子)    
        rotation:獲取隨機四元數
        insideUnitCircle:在半徑為1的圓內隨機生成位置(2個點)
            transition.position = Random.insideUnitCircle * 5;  在半徑為5的圓內隨機生成位置
        insideUnitSphere:在半徑為1的球內隨機生成位置(3個點)
            cube.position = Random.insideUnitSphere * 5;

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

public class API12Random : MonoBehaviour {

    void Start()
    {
        Random.InitState((int)System.DateTime.Now.Ticks);
        print(Random.Range(4, 10));
        print(Random.Range(4, 5f));

    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            print(Random.Range(4, 100));
            print((int)System.DateTime.Now.Ticks);
        }
        //cube.position = Random.insideUnitCircle * 5;
        this.transform.position = Random.insideUnitSphere * 5;
    }
}

四元數Quaternion

一個物體的transform元件中,rotation是一個四元數

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

public class API13Quaternion : MonoBehaviour {

    void Start()
    {
        // rotation:四元數
	    // eulerAngles:尤拉角,rotation中的x,y,z
        //this.transform.rotation = new Vector3(10, 0, 0);  錯誤,左邊是四元數,右邊是尤拉角
        this.transform.eulerAngles = new Vector3(10, 0, 0);
        print(this.transform.eulerAngles);
        print(this.transform.rotation);


        // Euler:將尤拉角轉換為四元數
        // eulerAngles:將四元數轉換為尤拉角
        this.transform.eulerAngles = new Vector3(45, 45, 45);
        this.transform.rotation = Quaternion.Euler(new Vector3(45, 45, 45));
        print(this.transform.rotation.eulerAngles);
    }

    public Transform player;
    public Transform enemy;
    void Update()
    {
        // LookRotation:控制Z軸的朝向,一般處理某個物體望向某個物體  案例:主角望向敵人
        // Lerp:插值,比Slerp快,但當角度太大的時候,沒Slerp效果好
        // Slerp:插值         案例:主角緩慢望向敵人
        if (Input.GetKey(KeyCode.Space))
        {
            Vector3 dir = enemy.position - player.position;
            dir.y = 0;
            Quaternion target = Quaternion.LookRotation(dir);
            player.rotation = Quaternion.Lerp(player.rotation, target, Time.deltaTime);
        }
    }
}

剛體Rigibody

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

public class API14RigidbodyPosition : MonoBehaviour {

    public Rigidbody playerRgd;
    public Transform enemy;
    public int force = 10;

    void Update()
    {
        // position:可以使用剛體的position來改變位置,突然改變
        playerRgd.position = playerRgd.transform.position + Vector3.forward * Time.deltaTime * 10;

        // MovePosition(Vector3 position):移動到目標位置,有插值的改變
        playerRgd.MovePosition(playerRgd.transform.position + Vector3.forward * Time.deltaTime * 10);

        // rotation:可以使用剛體的rotation來控制旋轉
        // MoveRotation:旋轉,有插值的改變
        if (Input.GetKey(KeyCode.Space))
        {
            Vector3 dir = enemy.position - playerRgd.position;
            dir.y = 0;
            Quaternion target = Quaternion.LookRotation(dir);
            playerRgd.MoveRotation(Quaternion.Lerp(playerRgd.rotation, target, Time.deltaTime));
        }

        // AddForce:給物體新增一個力
        playerRgd.AddForce(Vector3.forward * force);
    }
}

Camera

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

public class API15Camera : MonoBehaviour {

    private Camera mainCamera;

    void Start()
    {
        // 獲取攝像機
        //mainCamera= GameObject.Find("MainCamera").GetComponent<Camera>();
        mainCamera = Camera.main;
    }

    void Update()
    {
        // ScreenPointToRay:把滑鼠點轉換為射線
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

        // 射線碰撞到的遊戲物體
        RaycastHit hit;
        bool isCollider = Physics.Raycast(ray, out hit);  //射線檢測
        // 如果碰撞到物體,輸出物體名字
        if (isCollider)
        {
            Debug.Log(hit.collider);
        }

        Ray ray = mainCamera.ScreenPointToRay(new Vector3(200, 200, 0));
        Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
    }
}

Application類

Application Datapath:

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

public class API16Application_xxxPath : MonoBehaviour {
    void Start()
    {
        // 資料路徑,工程路徑
        print(Application.dataPath);
        // 可以通過檔案流讀取的資料
        // 注:單獨建立StreamingAssets資料夾,在此資料夾中的資料打包的時候不會進行處理
        print(Application.streamingAssetsPath);
        // 持久化資料
        print(Application.persistentDataPath);
        // 臨時緩衝資料
        print(Application.temporaryCachePath);
    }
}

Application 常用:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class API17Application : MonoBehaviour {

    void Start()
    {
        print(Application.identifier);// 標識 
        print(Application.companyName);// 公司名
        print(Application.productName);// 產品名字
        print(Application.installerName);// 安裝名
        print(Application.installMode);
        print(Application.isEditor);
        print(Application.isFocused);
        print(Application.isMobilePlatform);
        print(Application.isPlaying);
        print(Application.isWebPlayer);
        print(Application.platform);
        print(Application.unityVersion);
        print(Application.version);
        print(Application.runInBackground);

        Application.Quit();// 退出應用
        Application.OpenURL("www.sikiedu.com");// 開啟一個網址
        //Application.CaptureScreenshot("遊戲截圖");  // 棄用
        UnityEngine.ScreenCapture.CaptureScreenshot("遊戲截圖");//  截圖,引數是儲存截圖的名字

    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //UnityEditor.EditorApplication.isPlaying = false;
            SceneManager.LoadScene(1);
        }
    }
}

場景管理SceneManager:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class API18SceneManager : MonoBehaviour {

    void Start()
    {
        // 當前載入的場景數量
        print(SceneManager.sceneCount);
        // 在BuildSetting裡的場景數量
        print(SceneManager.sceneCountInBuildSettings);
        // 得到當前場景  通過name可以獲得名字
        print(SceneManager.GetActiveScene().name);
        // 根據index獲取場景,注意index只能是已經載入場景的
        print(SceneManager.GetSceneAt(0).name);

        SceneManager.activeSceneChanged += OnActiveSceneChanged;
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    // 場景改變事件(要解除安裝的場景,要載入的場景)
    void OnActiveSceneChanged(Scene a, Scene b)
    {
        print(a.name);
        print(b.name);
    }

    // 載入場景(載入的場景,載入的模式)
    void OnSceneLoaded(Scene a, LoadSceneMode mode)
    {
        print(a.name + "" + mode);
    }

    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            // LoadScene:載入場景,可以通過名字或者序號載入 
            // LoadSceneAsync:非同步載入,可以取得載入場景的進度
            //SceneManager.LoadScene(1);
            //SceneManager.LoadScene("02 - MenuScene");
            print(SceneManager.GetSceneByName("02 - MenuScene").buildIndex);
            SceneManager.LoadScene(1);
        }

    }
}

射線檢測:

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

public class Player : MonoBehaviour {
	
	void Update () {
		// 建立一條射線:new Ray(起點,方向);
        Ray ray = new Ray(transform.position+transform.forward, transform.forward);

		// 檢測碰撞:返回值表示是否碰撞到物體    Physics.Raycast(射線[, 距離]);
        //bool isCollider = Physics.Raycast(ray);    	//無限距離
        //bool isCollider = Physics.Raycast(ray, 1);    //檢測1米距離
		
		// 檢測碰撞到哪個物體:  Physics.Raycast(射線, 碰撞資訊);
        RaycastHit hit;
        //bool isCollider = Physics.Raycast(ray, out hit);
		
		// 碰撞檢測時只檢測某些層:  Physics.Raycast(射線, 距離, 檢測層);
		// Mathf.Infinity表示無限距
        bool isCollider = Physics.Raycast(ray, Mathf.Infinity, LayerMask.GetMask("Enemy1", "Enemy2", "UI"));
        
        Debug.Log(isCollider);
        //Debug.Log(hit.collider);
        //Debug.Log(hit.point);
		
		//注:射線檢測的過載方法有很多,不止以上幾種
		//注:如果是2D的射線檢測,要使用Physics2D.Raycast(),使用時要保證物體添加了2D碰撞器 
		//注:上面的方法只會檢測碰撞到的第一個物體,如果要檢測碰撞到的所有物體,使用RaycastAll(),返回RaycastHit陣列 
    }
}

UGUI事件監聽:3種方法

1 拖拽:

2 程式碼新增:

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

public class UIEventManager : MonoBehaviour {

    public GameObject btnGameObject;
    public GameObject sliderGameObject;
    public GameObject dropDownGameObject;
    public GameObject toggleGameObject;

	// Use this for initialization
	void Start () {
        btnGameObject.GetComponent<Button>().onClick.AddListener(this.ButtonOnClick);
        sliderGameObject.GetComponent<Slider>().onValueChanged.AddListener(this.OnSliderChanged);
        dropDownGameObject.GetComponent<Dropdown>().onValueChanged.AddListener(this.OnDropDownChanged);
        toggleGameObject.GetComponent<Toggle>().onValueChanged.AddListener(this.OnToggleChanged);
    }

    void ButtonOnClick()
    {
        Debug.Log("ButtonOnClick");
    }
    void OnSliderChanged(float value)
    {
        Debug.Log("SliderChanged:" + value);
    }
    void OnDropDownChanged(Int32 value)
    {
        Debug.Log("DropDownChanged:" + value);
    }
    void OnToggleChanged(bool value)
    {
        Debug.Log("ToggleChanged:" + value);
    }

    // Update is called once per frame
    void Update () {
		
	}
}

3 通過實現介面:通過這種方式,只能監聽當前UGUI元件

    滑鼠相關事件或拖拽相關事件的實現

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
//interface
public class UIEventManager2 : MonoBehaviour//, IPointerDownHandler,IPointerClickHandler,IPointerUpHandler,IPointerEnterHandler,IPointerExitHandler
    ,IBeginDragHandler,IDragHandler,IEndDragHandler,IDropHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");
    }

    public void OnDrop(PointerEventData eventData)
    {
        Debug.Log("OnDrop");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("OnPointerClick");
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("OnPointerDown");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("OnPointerEnter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("OnPointerExit");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("OnPointerUp");
    }
}

WWW類:下載專用

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

public class WWWTest : MonoBehaviour {

    public string url = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2622066562,1466948874&fm=27&gp=0.jpg";
    IEnumerator Start()
    {
        WWW www = new WWW(url);
        yield return www;
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = www.texture;
    }
}

角色控制器CharacterController:物體需要新增Character Controller元件

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

public class PlayerCC : MonoBehaviour {

    public float speed = 3;
    private CharacterController cc;

	// Use this for initialization
	void Start () {
        cc = GetComponent<CharacterController>();
        
	}
	
	void Update () {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        cc.SimpleMove(new Vector3(h, 0, v) * speed);//有重力效果
        //cc.Move(new Vector3(h, 0, v) * speed * Time.deltaTime);//無重力效果
        Debug.Log(cc.isGrounded);//是否在地面
	}
    private void OnControllerColliderHit(ControllerColliderHit hit)//自帶的檢測碰撞事件
    {
        Debug.Log(hit.collider);
    }
}

網格Mesh和材質Material

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

public class MeshAndMat : MonoBehaviour {
    public Mesh mesh;
    private Material mat;

	void Start () {
        //GetComponent<MeshFilter>().sharedMesh = mesh;//改變網格,樣子跟著變
        //Debug.Log(GetComponent<MeshFilter>().mesh == mesh);//改變網格,樣子不變
        mat = GetComponent<MeshRenderer>().material;
        
	}
	
	void Update () {
        mat.color = Color.Lerp(mat.color, Color.red, Time.deltaTime);//改變材質顏色
	}
}

unity 4.x   5.x   2017的異同

    GetComponent<Rigidbody2D>() 代替 rigidbody2D
    GetComponent<Rigidbody>() 代替 rigidbody
    GetComponent<AudioSource>() 代替 audio

    Unity 5.3:
    ParticleSystem main = smokePuff.GetComponent<ParticleSystem>();
    main.startColor
    Unity 5.5+:
    ParticleSystem.MainModule main = smokePuff.GetComponent<ParticleSystem>().main;
    main.startColor

    SceneManagement 代替 Application

    OnLevelWasLoaded() 在 Unity 5中被棄用了,使用OnSceneLoaded代替

		public class UnityAPIChange : MonoBehaviour {
			private Rigidbody rgd;
			void Start () {
				rgd = GetComponent<Rigidbody>();
				SceneManager.sceneLoaded += this.OnSceneLoaded;
			}
			void OnSceneLoaded(Scene scene, LoadSceneMode mode)
			{

			}
			
			void Update () {
				//rigidbody.AddForce(Vector3.one);
				//rgd.AddForce(Vector3.one);
				//audio.Play();//棄用的
				//GetComponent<AudioSource>().Play();
				//GetComponent<Rigidbody2D>();

				//GetComponent<MeshRenderer>();

				//Application.LoadLevel("Level2");
				SceneManager.LoadScene("Scene2");
				Scene scene = SceneManager.GetActiveScene();
				SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
			}

			private void OnLevelWasLoaded(int level)  棄用
			{
				
			}
		}