在开发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);
}
}</