本節要點
1.金錢副本細節完善
1.主角戰斗
①主角碰撞到 Box,Box 消失后,在消失的位置生成 1 枚金幣;
②金幣設置為觸發器模式,且自身要不停的旋轉;
③主角編寫觸發器處理代碼,觸發銷毀金幣。
2.SendMessage 消息發送
1.SendMessage 函數
gameObject.SendMessage(string):通知這個游戲物體身上的腳本文
件中的“指定方法”執行。
參數說明:
String:方法名,要執行的方法的名稱;
2.完善金錢副本
①創建一個 GUIText 用于顯示分數;
②給金幣創建腳本,金幣獲取到 GUIText 組件的引用;
③在金幣腳本中編寫“增加分數”的函數;
④當金幣銷毀時,SendMessage 通知該“增加分數”函數執行。
關鍵代碼
GoldRotate
public class GoldRotate : MonoBehaviour {
//讓金幣旋轉
private Transform m_Transform;
//完善金幣,讓金幣分數喜愛是出來;
private GUIText m_GUIText;
// Use this for initialization
void Start () {
//獲取游戲對象組件
m_Transform=gameObject.GetComponent<Transform>();
//獲取游戲對象 gui組件
// GameObject.Find("Score");//在別的腳本通過find的方法能找到這個游戲對象;
m_GUIText=GameObject.Find("Score").GetComponent<GUIText>();
}
// Update is called once per frame
void Update () {
m_Transform.Rotate(Vector3.forward,10f);//有重載的方法,注意調用的是那個 參數1:旋轉的方向 參數2:旋轉的角度
}
//讓分數累加的方法; 因為金幣消失時候給你發條消息通知你累計,所以必須是公開的;
int s = 0;//定義初始分數
public void AddScore() {
s = int.Parse(m_GUIText.text);//默認是字符串,必須強轉 才能累加
//檢查有沒有打印
// Debug.Log(s);
s++;
m_GUIText.text = s.ToString();//(s++)+"";
}
}
小結
Unity API.png