Unity的C#編程教程_48_帶參數的方法
2. Method Parameters
-
我們使用方法,來創建模組化的編程,這樣程式看起來簡潔,思路也更為清晰。而不是把所有程式都直接堆進 Update 裡面去
-
比如我們遊戲中的各種典型場景,可以分別放入對應的方法中
- 攻擊場景:計算傷害,造成扣血
- 吃 Buff 的場景:提升某種能力
-
這樣做的好處是,如果哪一塊程式碼出了問題,那麼我們可以很好去定位
-
而 Update 中,最好只放監控程式,即收集遊戲運行中的各種指標和數據,而具體的指標運算和回饋遊戲效果,可以放到專門的方法中執行
-
另外,方法名通常首字母大寫,長的名字可以配合駝峰法則
-
即然方法是用來做特定計算的,那如何傳入計算數據,計算完成後又如何讀取數據呢?
傳入參數:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Sum(5, 4); // 調用方法的時候,傳入與指定類型即個數相符合的參數
}
// Update is called once per frame
void Update()
{
}
private void Sum(int a,int b) // 設定需要傳入參數的個數和類型
{
Debug.Log(a + b); // 在方法的語句中運用這些參數進行運算
}
}
以此設計一個傷害扣血方法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public int health;
public int hit;
// Start is called before the first frame update
void Start()
{
health = 100; // 遊戲初始化的時候,角色 100 點血量
hit = 10; // 每次攻擊扣血 10 點
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) // 假設按下空格鍵就是受到了攻擊
{
Damage(hit); // 調用方法計算攻擊傷害
}
}
private void Damage(int getHit) // 設定需要傳入參數為傷害,類型 int
{
health -= getHit; // 計算扣血後的血量
if (health > 0)
{
Debug.Log("Health: " + health);
}
else
{
health = 0; // 如果血量低於 0,則把血量設置為 0
Debug.Log("Health: " + health);
Destroy(this.gameObject); // 血量扣到 0,則在 unity 中銷毀這個遊戲對象
}
}
}
把這個腳本掛載到一個遊戲對象上(比如一個 cube 上面),當你不斷按下空格鍵扣血到 0,這個遊戲對象就會被銷毀。
其實在方法中,我們不僅僅可以傳入 int 類型的數字,還可以傳入字元串,甚至直接傳入遊戲對象,然後在方法裡面進行運算和操作,比如上面的例子,我們可以直接把 cube 的遊戲對象傳到方法中,然後在方法中進行對應操作。