为什么我的程序无法识别我的目标对象

时间:2017-04-24 02:35:21

标签: c# unity3d

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class AIController : MonoBehaviour {

[Header("Player interaction")]
[SerializeField] private GameObject target;
[SerializeField] private int damage;
[SerializeField] private float attackDelay;
[SerializeField] private float stunTime;
[SerializeField] private int health;

public int Health{
    get{return health; }
    set{ health = value;
        agent.speed = runningSpeed;
        agent.SetDestination(target.transform.position);
        onPatrol = false;
        if (health <= 0){
            Destroy(gameObject);
        }
    }
}

// Update is called once per frame
void Update () {
        CanAttack(target);
}

这里我想确保AI只有当他在AI前面并且在0.5米内时才会攻击玩家。我使用它而不是OnTriggerEnter的原因是AI只会最终攻击一次,然后只是站在玩家之上而不做任何进一步的事情

void CanAttack (GameObject other)
{
    Vector3 vectorToTarget = other.transform.position - transform.position;
    float angleToTarget = Vector3.Angle(transform.forward, vectorToTarget);

    if (angleToTarget <= FOV)
    {
        RaycastHit raycastData;
        if (Physics.Raycast(transform.position, vectorToTarget, out raycastData, .5f))
        {
            GameObject newTarget = raycastData.collider.gameObject;
            Attack(target);
        }
    }
}

我也使用了Attack(其他),但这仍然不起作用

void Attack(GameObject other)
{
    if (!hasAttacked)//if the AI has not recently attacked
    {
        if (!Player.isShieldOn)//if the player shield is not up
        {
            if (!Player.hasShieldBraclet)//if the player has the shield braclet
            {
                other.gameObject.GetComponent<Player>().Health -= damage - ShieldBraclet.dmgReduction;//reduce the amount of damage taken
            }
            else
            {
                other.gameObject.GetComponent<Player>().Health -= damage;//otherwise take normal damage
            }
            StartCoroutine("DelayAttack");//delay time until AI can attack again
        }
        else
        {
            StartCoroutine(Stun(stunTime));//if the shield was up stun this enemy
        }
    }
}

这用于确保AI在再次攻击之前等待片刻,这样玩家在触摸AI时不会立即死亡。

IEnumerator DelayAttack()
{
    hasAttacked = true;//the AI has attacked
    yield return new WaitForSeconds(attackDelay);//wait to attack again
    hasAttacked = false;//the AI can now attack again
}

}

在大多数情况下,一切运行正常但是当它到达代码以对玩家造成损害时,它告诉我对象引用未设置为对象的实例。我该如何解决这个问题?

特定的错误代码是:NullReferenceException:对象引用未设置为对象的实例Enemy.Attack(UnityEngine.GameObject other)。 这是指

other.gameObject.GetComponent<Player>().Health -= damage - ShieldBraclet.dmgReduction;//reduce the amount of damage taken

0 个答案:

没有答案