首页 > 解决方案 > 在玩家范围内如何使敌人攻击?

问题描述

所以我的游戏是一个 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);
        }
    }

标签: c#unity3d

解决方案


修复你的无限攻击循环:

// 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 */
    }
}

推荐阅读