Unity 3D:訪問另一個C#類中的屬性或方法
阿新 • • 發佈:2018-12-26
在開發Unity 3D 遊戲的過程中,經常遇到在某個C#類中訪問另一個C#類中的方法或屬性;比如:在Eenmy.cs中訪問PlayAttack.cs指令碼中的TakeDamage(int damage)方法(該方法控制主角受傷的情況),以實現當敵人攻擊主角時呼叫TakeDamage方法對主角進行受傷的處理。那麼,如何實現呢?有下面常用的三種方法:
1. 設定PlayerAttack類為單例模式
// PlayerAttack指令碼 public class PlayerAttack : MonoBehaviour { public static PlayerAttack _instance; // static關鍵字。 單例模式 void Awake(){ _instance = this;// 確保單例模式在使用前已被初始化 } public void TakeDamage(int damage){ // do something } }
// Enemy指令碼
public class Enemy : MonoBehaviour {
//
void Attack(){
// 當敵人攻擊主角時
PlayerAttack._instance.TakeDamage(20);
}
}
2. 把要訪問的方法設定為靜態方法
// PlayerAttack指令碼
public class PlayerAttack : MonoBehaviour {
public static void TakeDamage(int damage){
// do something
}
}
3. 通過SendMessage方法傳遞引數(SendMessage用法)// Enemy指令碼 public class Enemy : MonoBehaviour { // void Attack(){ // 當敵人攻擊主角時 PlayerAttack.TakeDamage(20); } }
// PlayerAttack指令碼
public class PlayerAttack : MonoBehaviour {
public void TakeDamage(int damage){
// do something
}
}
// Enemy指令碼 public class Enemy : MonoBehaviour { // void Attack(){ // 當敵人攻擊主角時 // 首先需要獲取掛PlayerAttack的主角 GameObject player = GameObject.FindGameObjectWithTag("PlayerBoy");// Unity中主角模型的標籤為PlayerBoy player.SendMessage("TakeDamage", 20); } }