我们打开上一篇43事件中心的项目,
![](https://i-blog.csdnimg.cn/direct/fd498f4288174716b2e97ba2d4f992c3.png)
本章要做的事情是给主角增加一个xxxCtrl.cs脚本,再创建一个xxxOpt.cs调用xxxCtrl.cs机制层利用事件中心再写一个主角战士平A对怪物的伤害
首先创建脚本:PlayerCtrl.cs
![](https://i-blog.csdnimg.cn/direct/3f3532d1576c48c085096e88208f38a0.png)
cs
using UnityEngine;
public class PlayerCtrl : MonoBehaviour{
BossCtrl bossCtrl;
public void Start() {
bossCtrl = FindObjectOfType<BossCtrl>();
}
public void SetPlayerHpValueChange(float attackValue){
bossCtrl.currentHp -= (int)((attackValue -
bossCtrl.defineValue) * (1 + Random.Range(-0.3f,0.3f)));
}
}
将xxxCtrl.cs脚本增加到主角资源框架上
![](https://i-blog.csdnimg.cn/direct/071dd4ca7fe84b489cf97da2916a9a98.png)
再创建脚本:PlayerOpt.cs
![](https://i-blog.csdnimg.cn/direct/7fbc8de5e2674b5698647776e2c35b72.png)
cs
using UnityEngine;
public class PlayerOpt : MonoBehaviour{
GameManager gm;
PlayerRayClickNavigation player;
#region 事件中心
BossCtrl bossCtrl;
PlayerCtrl playerCtrl;
Vector3 monsterPos;
Vector3 selfPos;
#endregion
public void Start(){
gm = GameManager.Instance;
player = gameObject.GetComponent<PlayerRayClickNavigation>();
#region 事件中心
bossCtrl = FindObjectOfType<BossCtrl>();
playerCtrl = gameObject.AddComponent<PlayerCtrl>();
EventCenter.Instance.AddEventListener<Vector3>("MonsterPositionChanged", OnMonsterPositionChanged);
monsterPos = GameObject.FindWithTag("Monster").gameObject.transform.position;
#endregion
}
void Update(){
#region 事件中心
selfPos = transform.position;
Player01A(selfPos, monsterPos);
#endregion
}
#region 事件中心
void Player01A(Vector3 selfPos, Vector3 monsterPos){
this.selfPos = selfPos;
this.monsterPos = monsterPos;
if (Vector3.Distance(selfPos, monsterPos) < 10){
if (player.changeProfess == 2){
if (Input.GetKeyDown(KeyCode.A)){
playerCtrl.SetPlayerHpValueChange(gm.infoSys.attackValue);
}
}
}
}
void OnDestroy(){
EventCenter.Instance.RemoveEventListener<Vector3>("MonsterPositionChanged", OnMonsterPositionChanged);
}
void OnMonsterPositionChanged(Vector3 newPosition){
monsterPos = newPosition;
Player01A(transform.position, monsterPos);
}
#endregion
}
再将该脚本增加到资源框架上
![](https://i-blog.csdnimg.cn/direct/c7adb5e99b9046b38c225a807ecd2d96.png)
保存后运行项目
![](https://i-blog.csdnimg.cn/direct/17a6027d54024859acfd2c0cf438ddfc.png)
本章利用事件中心实现了主角战士平A(按A键)对怪物血量造成伤害的效果
接下来的文章内容:
1.战士职业的伤害型技能
2.窗口可拖拽脚本
3.点击名称寻找地点功能
4.隐藏怪物的生成
5.怪物I攻击范围内的主动攻击
6.掉落坐骑蛋的获取
7.异步传送转换场景
以及开放回合制、坐骑系统、宠物系统、背包系统、神炼系统、商城系统、Boss的目标跟随任务导航系统以及UI播放3D动画效果等等。
具体项目运行效果请关注water1024的b站视频项目演示《破碎纪元》
![](https://i-blog.csdnimg.cn/direct/211d8c82f60343d0b39b9880359e85a4.png)