Unity 5.x遊戲開發指南筆記(一)

使用UnityGUI

首先先創建一個空的GameObject,編寫腳本

using System.Collections.Generic;
using UnityEngine;

public class ShowName : MonoBehaviour {
    string text = "";
    string myName = "";
    void OnGUI()
    {
        //用標籤顯示文本
        GUILayout.Label("請輸入你的名字");
        //用文本區域輸入名字
        text = GUILayout.TextField(text);
        if (GUILayout.Button("提交"))
        {
            myName = text;
        }
        //當myName不爲空時,說明已經提交了名字
        if (!string.IsNullOrEmpty(myName))
        {
            GUILayout.Label("提交成功,名字: " + myName)
        }
    }
}

將該腳本作爲組件添加到之前創建的GameObject上即可

GUILayout是自動佈局的

調試

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

public class TestDebug : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Debug.Log("普通信息");
        Debug.LogWarning("警告信息");
        Debug.LogError("錯誤信息");
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

遊戲對象的創建

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

public class CreateGameObject : MonoBehaviour {

    void OnGUI()
    {
        if(GUILayout.Button("創建立方體",GUILayout.Height(50)))
        {
            //設置該模型默認爲立方體
            GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
            //爲對象添加一個剛體,賦予物理屬性
            obj.AddComponent<Rigidbody>();
            //賦予對象的材質紅色
            obj.GetComponent<Renderer>().material.color = Color.red;
            //設置對象的名稱
            obj.name = "Cube";
            //設置此模型材質的位置座標
            obj.transform.position = new Vector3(0,5f,0);
        }
        if(GUILayout.Button("創建球體",GUILayout.Height(50)))
        {
            //設置該模型默認爲立方體
            GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            //爲對象添加一個剛體,賦予物理屬性
            obj.AddComponent<Rigidbody>();
            //賦予對象的材質綠色
            obj.GetComponent<Renderer>().material.color = Color.green;
            //設置對象的名稱
            obj.name = "Sphere";
            //設置此模型材質的位置座標
            obj.transform.position = new Vector3(0,5f,0);
        }
    }
}

基本函數

AddComponent函數是會自動添加依賴的。當添加組件時,其依賴的組件也會被自動添加。例如關節HingeJoint依賴剛體Rigidbody,當添加HingeJoint時,如果Rigidbody未添加,則Rigidbody也會被自動添加到遊戲對象上

renderer.material.color設置渲染材質的顏色

transform.position設置遊戲對象的位置,該位置是位於世界座標系下的。如果要設置物體座標系下的位置,即相對於父節點下的位置,則用到的是transform.localPosition

獲取遊戲對象

方法一

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

public class GetGameObject1 : MonoBehaviour {

    public GameObject obj;
    void Start()
    {
        obj.GetComponent<Renderer>().material.color = Color.red;
    }
}

這裏在代碼當中定義了一個obj對象,但是obj對象還沒有綁定到已存在的模型上。可以先把他當做組件放到之前創建的gameobject上,打開Inspector界面在這裏插入圖片描述)]

可以看到obj對象還沒有指定相應的遊戲對象。

先在Hierarchy視圖中創建一個TestCube的cube模型,如圖所示

在這裏插入圖片描述

用鼠標選中TestCube,將其拖動到上圖None(Game Object)的位置,拖動後,發現
在這裏插入圖片描述
TestCube已經綁定到obj上了,運行場景

在這裏插入圖片描述

新創建的cube被改爲紅色了

方法二

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

public class GetGameObject2 : MonoBehaviour {

	// Use this for initialization
    private GameObject obj;
	void Start () {
        obj = GameObject.Find("TestCube");
        obj.GetComponent<Renderer>().material.color = Color.red;
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

直接通過GameObject.Find()獲取全局下name爲TestCube的遊戲對象,將其顏色改爲紅色,直接將其作爲組件添加給上述的GameObject,運行場景,效果和方法一一致,cube變爲紅色。

添加組件與修改組件

添加組件時主要使用AddComponent方法,而刪除組件時,需要使用Object.Destroy()方法,參數爲需要刪除的遊戲對象或組件。需要注意的是:如果要刪除的是某一遊戲對象,則這個遊戲對象下的所有組件也會被一併刪除

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

public class AlterComponent : MonoBehaviour {
    public Texture texture;
    private GameObject obj;
    private Renderer renderer;
	// Use this for initialization
	void Start () {
		//獲取遊戲對象
        GameObject obj = GameObject.Find("TestCube");
        //獲取該對象的渲染器
        renderer = obj.GetComponent<Renderer>();
	}

    void OnGUI()
    {
        if(GUILayout.Button("添加顏色",GUILayout.Width(100),GUILayout.Height(50)))
        {
            //修改渲染顏色爲紅色
            renderer.material.color = Color.red;
        } 
        if(GUILayout.Button("添加貼圖",GUILayout.Width(100),GUILayout.Height(50)))
        {
            //添加組件貼圖
            renderer.material.mainTexture = texture;
        }
    }
}

這裏隨便選了一張圖片作爲貼圖,綁定到texture屬性上

在這裏插入圖片描述
運行結果如下:

在這裏插入圖片描述
在這裏插入圖片描述

發送廣播與消息

遊戲對象之間的互動可以通過廣播來傳遞消息。

廣播函數原型:

GameObject.SendMessage(string methodName,object value = null,SendMessageOptions options = SendMessageOptions.RequireReceiver)

調用這個函數,會向這個遊戲對象所有的腳本發送信息。第一個參數是消息的名稱,所有Monobehavior腳本里與該名稱同名的方法將被調用,第二個參數是向該方法傳遞的參數,第三個參數是是否必須有接受方法的選項,一般選不要求接受方法即可。

//發送方
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SendMessage : MonoBehaviour {

	// Use this for initialization
    public GameObject receiver;
	void Start () {
        receiver.SendMessage("ShowNumber", 100, SendMessageOptions.DontRequireReceiver);
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}
//接受方
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ReceiveMessage : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    void ShowNumber(int number)
    {
        Debug.Log("收到的數字是 : " + number);
    }
}

在這裏插入圖片描述

綁定Receiver的遊戲對象

克隆

克隆指克隆具有一定功能的現成的對象,如果這個現成的對象已經被保存爲文件的話,則稱之爲預製體。

使用Instantiate()函數完成克隆操作

首先,先製作一個預製體(prefebal)

一:在Assets文件中,右擊選擇Create,選擇Folder,創建一個文件夾,文件夾命名爲Prefebal

二:在該文件夾下右擊選擇Create,選擇Prefebal,創建了一個空的Prefebal

在這裏插入圖片描述

三:創建一個Cube,重命名爲TestPrefebal,將其拖到剛纔創建到空的prefebal中

在這裏插入圖片描述

這樣一個prefebal就創建完成了,此時可以先將hierarchy中創建的cube刪除

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

public class ClonePrefebal : MonoBehaviour {

	// Use this for initialization
    public GameObject prefebal;
	void Start () {
		//克隆預製體
        GameObject obj = Instantiate(prefebal) as GameObject;
        //設置遊戲對象obj的位置
        obj.transform.position = new Vector3(0, 3, 0);
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

老規矩,將其拖到一個Gameobject上

在這裏插入圖片描述
在這裏插入圖片描述
點擊小齒輪,可以看到當前已有的資源

在這裏插入圖片描述

搜索Test,將其綁定到Prefebal上
在這裏插入圖片描述

運行場景,可以發現場景中多出了一個cube了

在這裏插入圖片描述

移動、旋轉、縮放遊戲對象

unity中,每個遊戲對象都會帶有transform屬性,即使這個遊戲對象其他屬性都沒有,但transform一定是會有的。比如我創建一個空的gameobject

在這裏插入圖片描述

transform屬性一定是存在的

這三個屬性的作用也如他們的英文名一樣,position設置的是該對象在世界座標系中的位置,Rotation設置該對象的旋轉角度,Scale設置該對象的縮放比例

移動遊戲對象

在界面中,按w即可移動

在這裏插入圖片描述
腳本中:

transform.Translate(Vector3 offset);
//相當於
transform.position = transform.position + offset;

縮放遊戲對象

在界面中,使用R

在這裏插入圖片描述

腳本中:

transform.localScale = new Vector3(x,y,z);
//如果三個軸的縮放比例一致的話,像下面這樣,三個方向上同時拉伸1.2倍
transform.localScale *= 1.2f

旋轉游戲對象

界面中,按e

在這裏插入圖片描述

腳本中:

//設置遊戲對象自轉
transform.Rotate()
//設置遊戲對象圍繞某一個點旋轉
transform.RotateAround()
//上一幀消耗的時間,用作模型旋轉的速度係數
Time.deltaTime
//x軸的正方向
Vector3.right
//y軸正方向
Vector3.up
//z軸正方向
Vector3.forward

在這裏插入圖片描述

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

public class AlterObject : MonoBehaviour {

	//遊戲對象一定要設置成public,否則無法完成綁定
    public GameObject cube;

    public GameObject cylinder;
    void OnGUI()
    {
        if (GUILayout.Button("向左移動物體"))
        {
            cube.transform.Translate(new Vector3(-0.5f, 0, 0));
        }
        if (GUILayout.Button("向右移動物體"))
        {
            cube.transform.Translate(new Vector3(0.5f, 0, 0));
        }
        if (GUILayout.Button("放大物體"))
        {
            cube.transform.localScale *= 1.2f;
        }
        if (GUILayout.Button("縮小物體"))
        {
            cube.transform.localScale *= 0.8f;
        }
        if(GUILayout.Button("旋轉物體")){
            cube.transform.Rotate(new Vector3(0, 10, 0));
        }
        if (GUILayout.Button("圍繞球體旋轉物體"))
        {
            cube.transform.RotateAround(cylinder.transform.position, Vector3.up, 10);
        }
    }
}

在這裏插入圖片描述

說明一下RotateAround(),第一個參數是指定旋轉的物體,第二個參數是指定旋轉的軸,第三個參數是旋轉的角度

工具類

//Time類
//當前遊戲時間
Time.time
//遊戲時間的縮放(即時間流逝的速度,爲1時,遊戲時間和真實世界的時間是一致的)
Time.timeScale
//上一幀所消耗的時間
Time.deltaTime
//固定增量時間(每一次執行FixedUpdate()函數的時間間隔。可通過“Edit""Project Settings""Time"菜單項設置
 Time.fixedDeltaTime
//固定更新上一幀所消耗的時間
Time.fixedDeltaTime
//真實逝去時間(截止到目前共運行的真實時間,不受Time.scale影響,遊戲暫停該時間仍然增加)
Time.realtimeSinceStartup

四元數

精確計算模型旋轉角度

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

public class RotateObject : MonoBehaviour {

    public GameObject obj;
    const float rotateSpeed = 50f;
	// Use this for initialization
	void Start () {
       
	}
	
	// Update is called once per frame
	void Update () {
        //模型繞y軸旋轉
        obj.transform.rotation = Quaternion.Euler(0f, rotateSpeed * Time.time, 0);
	}
}

輸入控制

PC端輸入指鍵盤和鼠標的輸入檢測,一般分爲3類,按下,按住,擡起

//按下A鍵
if(Input.GetKeyDown(KeyCode.A)){...}
//按住A鍵
if(Input.GetKey(KeyCode.A)) {...}
//擡起A鍵
if(Input.GetKeyUp(KeyCode.A)) {...}
//按下鼠標左鍵
if(Input.GetMouseButtonDown(0)){...}
//按住鼠標左鍵
if(Input.GetMouseButton(0)) {...}
//擡起鼠標左鍵
if(Input.GetMouseButtonUp(0)) {...}
//按下鼠標右鍵
if(Input.GetMouseButtonDown(1)){...}
//按住鼠標右鍵
if(Input.GetMouseButton(1)) {...}
//擡起鼠標右鍵
if(Input.GetMouseButtonUp(1)) {...}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章