c# - 在玩家范围内如何使敌人攻击?
问题描述
所以我的游戏是一个 2D 自上而下的运动游戏,我的脚本确实让我的敌人攻击,但它不断循环攻击动画,因为我显然不知道在玩家范围内时到底该放什么代码来让敌人攻击造成伤害,而不是让他不断循环。此外,当我接近我的敌人时,我似乎遇到了一个错误,因为现在它说
NullReferenceException:对象引用未设置为对象实例 EnemyCombat.Attack ()(在 Assets/EnemyCombat.cs:36) EnemyCombat.Update ()(在 Assets/EnemyCombat.cs:25)
另外,这是 EnemyCombat 脚本
enemy attausing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCombat : MonoBehaviour
{
public Animator animator;
public Transform AttackPoint;
public float attackRange = 0.5f;
public LayerMask enemyLayers;
public int attackDamage = 5;
public float attackRate = 2f;
float nextAttackTime = 0f;
// Update is called once per frame
void Update()
{
if (Time.time >= nextAttackTime)
{
Attack();
nextAttackTime = Time.time + 1f / attackRate;
}
}
void Attack()
{
animator.SetTrigger("Attack");
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackPoint.position, attackRange, enemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
}
}
void OnDrawGizmosSelected()
{
if (AttackPoint == null)
return;
Gizmos.DrawWireSphere(AttackPoint.position, attackRange);
}
}
解决方案
修复你的无限攻击循环:
// Update is called once per frame
void Update()
{
if (attackRate >= nextAttackTime) /* checks that nextAttackTime is less than or equal to the attackRate */
{
Attack();
nextAttackTime = Time.deltaTime * 5f; // adds 5 seconds to nextAttackTime
}
else
{
nextAttackTime -= Time.deltaTime; /* if nextAttackTime is greater than the attackRate, subtract one from nextAttackTime. this only happens once per second because you use Time.deltaTime */
}
}
推荐阅读
- r - for循环中的多个图忽略par
- excel - Excel 数据操作 - 一行成多行
- jquery - 从 ajax 调用时,DataTable 不应用样式
- docker - 使用匹配标签时如何从 fluentd 中的 docker 中排除特定日志?
- android - Android Studio在listview项目上保存drawableLeft图标点击
- python - 不同列的相关性
- c++ - 为什么具有 2 个参数参数的构造函数接受复制对象作为 1 个参数参数?
- reactjs - Cloud Firestore ReactJS 错误:缺少权限或权限不足
- python - Python - 检查字符串的一部分是否存在于列表中并给出其匹配的索引
- javascript - 响应式过滤图片库 P