【发布时间】:2021-11-10 18:25:56
【问题描述】:
所以我的游戏是一个 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);
}
}
【问题讨论】:
-
听起来
animator、AttackPoint或GetComponent<Enemy>是null(我们不知道哪一行是36)...你试过Debugging your code 吗?