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  建立原始的幾何體dom

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):設置激活狀態ide

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

GameObject.Find和transform.Find的區別: 
public static GameObject Find(string name); 
適用於整個遊戲場景中名字爲name的全部處於活躍狀態的遊戲對象。若是在場景中有多個同名的活躍的遊戲對象,在屢次運行的時候,結果是固定的。this

public Transform Find(string name); 
適用於查找遊戲對象子對象名字爲name的遊戲對象,無論該遊戲對象是不是激活狀態,均可以找到。只能是遊戲對象直接的子游戲對象。url

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:發送消息,向上傳遞(父)pwa

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)  棄用
			{
				
			}
		}
相關文章
相關標籤/搜索