如何在敌人越过对撞机后停止连续射击自动炮塔?

时间:2014-12-11 12:43:20

标签: unity3d

我有一个炮塔,作为一个游戏对象,当一个敌人进入它的碰撞盒时,炮塔开始射向它,逻辑是当敌人离开对战时,它应该停止射击,以及其他问题就是当敌人再次进入碰撞盒即第二个敌人时,它会给我一个例外," MissingReferenceException:类型'变换的对象'已被销毁,但你仍然试图访问它。你的脚本应该检查它是否为空或你不应该销毁它"但我正在检查我的代码中的列表是否为空。这是我的代码

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

public class TurretScript : MonoBehaviour {

public float shotInterval = 0.2f; // interval between shots
public GameObject bulletPrefab; // drag the bullet prefab here
public float bulletSpeed;

private float shootTime = 0.0f;
private List<Transform> targets;
private Transform selectedTarget;
private Transform myTransform;
private Transform bulletSpawn;

void Start(){
    targets = new List<Transform>();
    selectedTarget = null;
    myTransform = transform;
    bulletSpawn = transform.Find ("bulletSpawn"); // only works if bulletSpawn is a turret child!
}

    void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "enemy"){ // only enemies are added to the target list!
        targets.Add(other.transform);

    }
}

void OnTriggerExit2D(Collider2D other){
    if (other.tag == "enemy"){
        targets.Remove(other.transform);
        Debug.Log("gone out");
    }
}

void TargetEnemy(){
    if (selectedTarget == null){ // if target destroyed or not selected yet...
        SortTargetsByDistance();  // select the closest one
        if (targets.Count > 0) selectedTarget = targets[0];
    }
}

void SortTargetsByDistance(){
    targets.Sort(delegate(Transform t1, Transform t2){ 
        return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
    });
}

void Update(){
    TargetEnemy(); // update the selected target and look at it
    if (selectedTarget)
     { 
        // if there's any target in the range...
        Vector3 dir = selectedTarget.position - transform.position;
        float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);// aim at it
        if (Time.time >= shootTime){// if it's time to shoot...
            // shoot in the target direction
            Vector3 lookPos = new Vector3(bulletSpawn.position.x,bulletSpawn.position.y,0);
            lookPos = lookPos - transform.position;
            float ang = Mathf.Atan2(lookPos.y,lookPos.x)*Mathf.Rad2Deg;
            GameObject b1 = Instantiate(bulletPrefab,new Vector3(transform.position.x,transform.position.y,5),transform.rotation)as GameObject;
            b1.rigidbody2D.velocity = new Vector3(Mathf.Cos(ang*Mathf.Deg2Rad),Mathf.Sin(ang*Mathf.Deg2Rad),0)*bulletSpeed;

            shootTime = Time.time + shotInterval; // set time for next shot
        }
    }
}
}

这是我的敌人脚本

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

public class EnemyScript : MonoBehaviour {

public Transform target;
public float speed = 2f;

public int Health;

public float GetHealth()
{
    return Health; 
}


void Update ()
{
    transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);                                                                     
}

void TakeDamage(int damage){
    Health -= damage;
    if (Health <= 0) 
        Destroy(gameObject);
}


void OnTriggerEnter2D(Collider2D otherCollider)
{
    PlayerControl shot = otherCollider.gameObject.GetComponent<PlayerControl>();
    if (shot != null)
    {
        SpecialEffectsHelper.Instance.Explosion(transform.position);
        Destroy(shot.gameObject); 
    }
}

}

1 个答案:

答案 0 :(得分:0)

您需要检查所选目标是否是离开对撞机的目标。您从目标列表中删除了目标,但仍然填充了selectedTarget var。

对于null ref异常。您使用Destroy()来杀死目标吗? Destroy() {}未导致OnTriggerExit()OnCollisionExit()事件调用,该对象已消失。

编辑:您可以通过向垂死对象添加OnDestroy()功能来解决缺少呼叫的问题,该功能将其设置为远离玩家等级/视图的位置。这样,目标离开对撞机然后消失,而不是仅仅消失在原位。